如何对UrlHelper自定义帮助器方法进行单元测试

Bre*_*ogt 3 asp.net asp.net-mvc nunit asp.net-mvc-3 asp.net-mvc-2

我正在使用ASP.NET MVC 3NUnit.我正在尝试编写一个单元来测试我的一个辅助方法.这里是:

public static class UrlHelperAssetExtensions
{
   private static readonly string yuiBuildPath = "http://yui.yahooapis.com/2.8.2r1/build/";

   public static string YuiResetFontsGridsStylesheet(this UrlHelper helper)
   {
      return helper.Content(yuiBuildPath + "reset-fonts-grids/reset-fonts-grids.css");
   }
}
Run Code Online (Sandbox Code Playgroud)

这是我的单元测试:

[Test]
public void YuiResetFontsGridsStylesheet_should_return_stylesheet()
{
   // Arrange
   RequestContext requestContext = new RequestContext();
   UrlHelper urlHelper = new UrlHelper(requestContext);

   // Act
   string actual = urlHelper.YuiResetFontsGridsStylesheet();

   // Assert
   string expected = yuiBuildPath + "reset-fonts-grids/reset-fonts-grids.css";
   Assert.AreEqual(expected, actual);
}
Run Code Online (Sandbox Code Playgroud)

我测试它的方法是否正确?当我在NUnit GUI中运行它时,我收到以下错误:

System.ArgumentNullException:值不能为null.参数名称:httpContext

这有可能测试吗?如果是这样,请明确说明如何获取httpContext的实例?

更新

我无法通过这项测试.在我的方法中,我有以下内容:

private static readonly string stylesheetPath = "~/Assets/Stylesheets/";

public static string Stylesheet(this UrlHelper helper)
{
   return helper.Content(stylesheetPath + "MyStylesheet.css");
}
Run Code Online (Sandbox Code Playgroud)

我为它写的测试如下:

private string stylesheetPath = "/Assets/Stylesheets/";
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 Stylesheet_should_return_stylesheet()
{
   // Act
   string actual = urlHelper.Stylesheet();

   // Assert
   string expected = stylesheetPath + "MyStylesheet.css";
   Assert.AreEqual(expected, actual);
}
Run Code Online (Sandbox Code Playgroud)

NUnit GUI出现以下错误:

System.NullReferenceException : Object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)

似乎是在〜中出现错误:

private static readonly string stylesheetPath = "~/Assets/Stylesheets/";
Run Code Online (Sandbox Code Playgroud)

Jak*_*cki 9

你需要模拟HttpContext.以下是使用Moq的示例:

// Arrange
   var context = new Mock<HttpContextBase>();
   RequestContext requestContext = new RequestContext(context.Object, new RouteData());
   UrlHelper urlHelper = new UrlHelper(requestContext);
Run Code Online (Sandbox Code Playgroud)

如果您不想使用模拟框架,则可以创建一个将从HttpContextBase派生并使用它的类.但这需要实现许多抽象成员,你可以通过嘲笑来避免这些成员.