繁体   English   中英

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

[英]Create a unit test for a cookie creator static method

我在静态类中有此静态方法:

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

总是在Web表单后面的代码中调用它。 永远不在presenter层。

我究竟做错了什么?

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

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

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

我相信你需要设置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]),
    };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM