我正在使用MVC5来创建一个基于文化的项目。我正在使用MOQ为我的应用程序创建一些测试用例,但我无法在此找到我的路由。我正在使用一个名为MockHttpContext的类来获取我的httpcontext,如下所示。
public static HttpContextBase MockHttpContext()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
var urlHelper = new Mock<UrlHelper>();
var routes = new RouteCollection();
RouteTable.Routes.Clear();
var areaRegistration = new AdminAreaRegistration();
var areaRegistrationContext = new AreaRegistrationContext(
areaRegistration.AreaName, RouteTable.Routes);
areaRegistration.RegisterArea(areaRegistrationContext);
RouteConfig.RegisterRoutes(RouteTable.Routes);
var requestContext = new Mock<RequestContext>();
requestContext.Setup(x => x.HttpContext).Returns(context.Object);
context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
context.Setup(ctx => ctx.Session).Returns(session.Object);
context.Setup(ctx => ctx.Server).Returns(server.Object);
context.Setup(ctx => ctx.User).Returns(user.Object);
user.Setup(ctx => ctx.Identity).Returns(identity.Object);
identity.Setup(id => id.IsAuthenticated).Returns(true);
identity.Setup(id => id.Name).Returns("test");
request.Setup(req => req.Url).Returns(new Uri("http://localhost/"));
request.Setup(req => req.RequestContext).Returns(requestContext.Object);
requestContext.Setup(x => x.RouteData).Returns(new RouteData());
request.SetupGet(req => req.Headers).Returns(new NameValueCollection());
return context.Object;
}
//this method is being called in my test class like..
[TestMethod]
public void Index()
{
try
{
var controller = new HomeController();
var httpContext = MvcMockHelpers.MockHttpContext();
var routeData = RouteTable.Routes.GetRouteData(httpContext);
controller.SetMockControllerContext(
httpContext, routeData, RouteTable.Routes);
ViewResult result = controller.Index() as ViewResult;
Assert.AreEqual(result, ErrorResources.Error);
}
catch(Exception ex)
{
throw ex;
}
}
但问题是这样的:每当我试图在我的实用程序中获取我的上下文时 使用下面的线来获得文化。
var context = new HttpContextWrapper(System.Web.HttpContext.Current);
var routeData = RouteTable.Routes.GetRouteData(context);
var code = routeData.Values[Constants.CULTURE];
我得到的上下文返回空路由,意味着Route和RouteHandler为null,键/值也为0,所以我试着检查这一行。
requestContext.Setup(x => x.RouteData).Returns(new RouteData());
在这一行中,new RouteData()
为空,即使我之前已经注册过它。那么在这种情况下如何才能获得RouteData()
?
答案 0 :(得分:0)
问题是微不足道的,因为你没有使用模拟的HttpContextBase。 用以下内容替换第二个代码块。
var context = MockHttpContext();
var routeData = RouteTable.Routes.GetRouteData(context);
var code = routeData.Values[Constants.CULTURE];