我正在使用 ASP.NET MVC 3
和 NUnit
。我正在尝试编写一个单元来测试我的一个辅助方法。这是:
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/