我有一些UrlHelper
扩展方法,我想进行单元测试。但是,当路径以“〜/”开头时,我从NullReferenceException
方法获得UrlHelper.Content(string)
。谁知道问题是什么?
[Test]
public void DummyTest()
{
var context = new Mock<HttpContextBase>();
RequestContext requestContext = new RequestContext(context.Object, new RouteData());
UrlHelper urlHelper = new UrlHelper(requestContext);
string path = urlHelper.Content("~/test.png");
Assert.IsNotNullOrEmpty(path);
}
答案 0 :(得分:10)
使用RouteContext创建UrlHelper时,单元测试环境中的HttpContext为null。如果没有它,当你尝试调用任何依赖它的方法时,你会遇到很多NullReferenceExceptions。
有很多线程在嘲笑各种网络环境。你可以看一下这个: How do I mock the HttpContext in ASP.NET MVC using Moq?
或者这个 Mock HttpContext.Current in Test Init Method
修改强> 以下将有效。请注意,您需要模拟HttpContext.Request.ApplicationPath和HttpContext.Response.ApplyAppPathModifier()。
[Test]
public void DummyTest() {
var context = new Mock<HttpContextBase>();
context.Setup( c => c.Request.ApplicationPath ).Returns( "/tmp/testpath" );
context.Setup( c => c.Response.ApplyAppPathModifier( It.IsAny<string>( ) ) ).Returns( "/mynewVirtualPath/" );
RequestContext requestContext = new RequestContext( context.Object, new RouteData() );
UrlHelper urlHelper = new UrlHelper( requestContext );
string path = urlHelper.Content( "~/test.png" );
Assert.IsNotNullOrEmpty( path );
}
我在以下主题中找到了相关的详细信息: Where does ASP.NET virtual path resolve the tilde "~"?