为cookie创建者静态方法创建单元测试

时间:2013-09-12 14:37:38

标签: c# webforms nunit moq mvp

我在静态类中有这个静态方法:

public static class CookieHelper //:ICookieHelper
{
    public static void CreateCookie(string cookieName, int expireyDays)
    {
        HttpCookie cookie;
        cookie = HttpContext.Current.Response.Cookies[cookieName]; //Exception is here
        cookie.Expires.AddDays(expireyDays);
    }
}

我为它写了这个单元测试。运行此测试会生成nullreferenceexception(对象引用未设置为...)。

[Test]
public void ShouldCreateCookieAndValidateNotNull()
{
    string newCookie = "testCookie";

    CookieHelper.CreateCookie(newCookie,5);

    string cookieValue = HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request[newCookie]);

    Assert.NotNull(cookieValue);
}

这总是在webform后面的代码中调用;永远不会在演示者层。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您正在将您的实现与HttpContext.Current紧密结合,这不是一个好主意。

我建议您重新创建助手以接受用于创建Cookie的HttpContextBase。甚至是HttpResponseBase,因为它根本不需要上下文。

然后,从控制器中,您可以使用当前控制器上下文(或响应)传递给帮助程序。

答案 1 :(得分:0)

我认为您需要在测试初始化​​期间将HttpContext.Current设置为新的HttpContext并使用新的HttpResponse

HttpContext.Current = new HttpContext(
    new HttpRequest("", "http://tempuri.org", "ip=127.0.0.1"),
    new HttpResponse(new StringWriter()))
    {
        User = new GenericPrincipal(
            new GenericIdentity("username"),
            new string[0]),
    };