1
我正在使用MVC5在文化基礎上創建項目。我正在使用起訂量爲我的應用程序創建一些測試用例,但我無法在此找到我的路線。我正在使用名爲MockHttpContext的類來獲取我的httpcontext,如下所示。無法在MVC項目中檢索RouteData
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];
這我返回空航線的情況下,意味着路由和RouteHandler是零和鍵/值也爲0,所以我試圖檢查此行。
requestContext.Setup(x => x.RouteData).Returns(new RouteData());
在這一行,new RouteData()
爲空,即使我之前已經註冊了。那麼在這種情況下,我怎麼能得到我的RouteData()
?
不,我們不能這樣做,因爲這是我用我的控制器端與邏輯端的基本功能,我們不能在我的實用工具類嘲笑這一點,如果這件事情正在被使用我的測試項目,然後肯定我嘲笑它...所以無論如何感謝您的答覆..我已經解決了這個問題,而不使用MOQ dll,我們創建自己的假Httpcontext,請求,響應和服務器是好的,我的測試用例現在使用最小起訂量可以很好地工作。 – 2014-12-05 10:55:34