我正在尝试将单元测试添加到我构建的ASP.NET MVC应用程序中.在我的单元测试中,我使用以下代码:
[TestMethod]
public void IndexAction_Should_Return_View() {
var controller = new MembershipController();
controller.SetFakeControllerContext("TestUser");
...
}
Run Code Online (Sandbox Code Playgroud)
使用以下帮助程序来模拟控制器上下文:
public static class FakeControllerContext {
public static HttpContextBase FakeHttpContext(string username) {
var context = new Mock<HttpContextBase>();
context.SetupGet(ctx => ctx.Request.IsAuthenticated).Returns(!string.IsNullOrEmpty(username));
if (!string.IsNullOrEmpty(username))
context.SetupGet(ctx => ctx.User.Identity).Returns(FakeIdentity.CreateIdentity(username));
return context.Object;
}
public static void SetFakeControllerContext(this Controller controller, string username = null) {
var httpContext = FakeHttpContext(username);
var context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
controller.ControllerContext = context;
}
}
Run Code Online (Sandbox Code Playgroud)
此测试类继承自具有以下内容的基类:
[TestInitialize]
public void Init() {
...
} …Run Code Online (Sandbox Code Playgroud) 我有以下由 Hangfire 执行的代码(没有 HttpContext),当我在本地运行时运行完美:
class FakeController : ControllerBase
{
protected override void ExecuteCore() { }
public static string RenderViewToString(string controllerName, string viewName, object viewData)
{
using (var writer = new StringWriter())
{
var routeData = new RouteData();
routeData.Values.Add("controller", controllerName);
var fakeControllerContext = new ControllerContext(
new HttpContextWrapper(
new HttpContext(new HttpRequest(null, "http://nopage.no", null)
, new HttpResponse(null))
),
routeData,
new FakeController()
);
var razorViewEngine = new RazorViewEngine();
var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, "", false);
var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View, new ViewDataDictionary(viewData), new …Run Code Online (Sandbox Code Playgroud)