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

标签 asp.net asp.net-mvc asp.net-mvc-2 asp.net-mvc-3 nunit

我正在使用 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");
   }
}

这是我的单元测试:

[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);
}

我测试的方法正确吗?当我在 NUnit GUI 中运行它时,出现以下错误:

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

这个可以测试吗?如果是这样,请清楚地解释如何获取 httpContext 的实例?

已更新

我无法通过此测试。在我的方法中,我有以下内容:

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

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

我为其编写的测试如下:

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);
}

NUnit GUI 出现以下错误:

System.NullReferenceException : Object reference not set to an instance of an object.

似乎在 ~ 中遇到错误:

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

最佳答案

您需要模拟 HttpContext。这是使用 Moq 的示例:

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

如果您不想使用模拟框架,您可以创建一个从 HttpContextBase 派生的类并使用它。但这需要实现大量抽象成员,您可以通过模拟它来避免这种情况。

关于asp.net - 如何对 UrlHelper 自定义帮助器方法进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5259644/

相关文章:

c# - Microsoft Graph - 允许用户访问应用程序/服务主体

c# - MVC 文本框验证问题

javascript - 如何使用URL获取cookie值?

asp.net-mvc - [HttpPost]public ActionResult Create(FormCollection集合)与[HttpPost]public ActionResult Create(晚餐)

c# - 使用 `String` 而不是 `Date` 类型时如何验证日期?

c# - 从行中的链接获取 gridview 行详细信息

asp.net - 在测试期间如何使电子邮件转到本地文件夹?

c# - 为什么 ASP.NET 找不到我的文本框?

javascript - ASP.NET MVC 和 Javascript/jQuery 的设置?

asp.net-mvc - 无法定义两个对象之间的关系,因为它们附加到不同的ObjectContext对象mvc 2