我正在使用ASP.NET MVC 3
和NUnit
。我正在嘗試編寫一個單元來測試我的一個輔助方法。那就是:如何單元測試UrlHelper自定義幫助程序方法
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/";
您的異常調用堆棧可以幫助 – 2011-03-10 14:14:18