I have this static method in a static class:

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

I wrote this unit test for it. Running this test is generating a nullreferenceexception (object reference not set to ...).

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

    CookieHelper.CreateCookie(newCookie,5);

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

    Assert.NotNull(cookieValue);
}

This is always invoked in code behind of a webform; never in the presenter layer.

What am I doing wrong?

有帮助吗?

解决方案

You are tightly coupling your implementation with HttpContext.Current, which is not a good idea.

I would suggest that you recreate your helper to accept HttpContextBase which it uses to create the cookie. Or even HttpResponseBase, as it does not need the context at all.

Then, from your controller you can use the current controller context (or response) to pass into the helper.

其他提示

I believe you need to set up HttpContext.Current as a new HttpContext with a new HttpResponse during your test initialization:

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归因
不隶属于 StackOverflow
scroll top