我正在使用ASP.NET MVC 3
和NUnit
。
我创建了一个辅助方法来返回一个动作方法(重载方法):
public static object CategoryIndex(this UrlHelper urlHelper)
{
return new { controller = "Category", action = "Index" };
}
public static string CategoryIndex(this UrlHelper helper, int categoryId)
{
return helper.RouteUrl(new { controller = "Category", action = "Index", id = categoryId });
}
失败的测试是第二个名为CategoryIndex_should_navigate_to_category_index_action_method_with_child_category_id()
的测试。
private HttpContextBase httpContextBaseStub;
private RequestContext requestContext;
private UrlHelper urlHelper;
[SetUp]
public void SetUp()
{
httpContextBaseStub = MockRepository.GenerateStub<HttpContextBase>();
requestContext = new RequestContext(httpContextBaseStub, new RouteData());
urlHelper = new UrlHelper(requestContext);
}
[Test]
public void CategoryIndex_should_navigate_to_category_index_action_method()
{
// Act
object actual = UrlHelperNavigationExtensions.CategoryIndex(urlHelper);
// Assert
RouteValueDictionary routes = new RouteValueDictionary(actual);
Assert.AreEqual("Category", routes["controller"]);
Assert.AreEqual("Index", routes["action"]);
}
[Test]
public void CategoryIndex_should_navigate_to_category_index_action_method_with_child_category_id()
{
// Arrange
int childCategoryId = 1;
// Act
string actual = UrlHelperNavigationExtensions.CategoryIndex(urlHelper, childCategoryId);
// Assert
Assert.AreEqual("/Category/Index/1", actual);
}
抱怨实际为空。为什么会这样,我将如何纠正它?
答案 0 :(得分:4)
在我看来,你没有初始化routecollection。我觉得这样的事情可以解决问题
[SetUp]
public void SetUp()
{
RouteCollection routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);
httpContextBaseStub = MockRepository.GenerateStub<HttpContextBase>();
requestContext = new RequestContext(httpContextBaseStub, new RouteData());
//urlHelper = new UrlHelper(requestContext);
urlHelper = new UrlHelper(requestContext, routes);
}
似乎也没有设置HttpContextBase。一定要正确地模拟它,否则你会得到一些空的引用异常。
[SetUp]
public void SetUp()
{
RouteCollection routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);
//httpContextBaseStub = (new Moq.Mock<HttpContextBase>()).Object;
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
response.Setup(r => r.ApplyAppPathModifier(It.IsAny<string>())).Returns((String url) => url);
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Setup(c => c.Request).Returns(request.Object);
mockHttpContext.Setup(c => c.Response).Returns(response.Object);
requestContext = new RequestContext(mockHttpContext.Object, new RouteData());
urlHelper = new UrlHelper(requestContext, routes);
}
答案 1 :(得分:1)
我的猜测是因为路由表是空的,所以它不知道如何生成URL。
添加普通/ {controller} / {action}路由,它应该可以正常工作。
(如果这是错误的话我会打电话原谅)
你需要存根一个IRouteHandler实现,我在这里称之为stub_handler。
RouteTable.Routes.Add(new Route
(
"{controller}/{action}/{id}"
, stub_handler
);