简体   繁体   中英

Create a unit test for a cookie creator static method

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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