Pankaja Gamage
Pankaja Gamage

Reputation: 304

MVC Unit Testing with Cookies

I'm having two projects for the unit testing and for my web project.

        AuthenticationController controller = new AuthenticationController();
        ViewResult result = controller.LogOut() as ViewResult;
        Assert.IsNotNull(result);

and in the project, I will be passing the http cookie and the authorization request.

When im running the LogOut test it will fail when getting the cookie. Is there any way to overcome this by creating a fake cookie or any other means?

Thanks in advance.

Upvotes: 2

Views: 1389

Answers (1)

Guest123456789
Guest123456789

Reputation: 11

Hope this helps! Alternatively use a mocking framework.

AuthenticationController controller = new AuthenticationController();
var httpContext = new MockHttpContext();
//set cookie

controller.ControllerContext = new ControllerContext(httpContext, controller);

public class MockHttpContext : HttpContextBase
{
    readonly HttpRequestBase _request;

    public MockHttpContext()
    {
        _request = new MockHttpRequest();
    }

    public override HttpRequestBase Request
    {
        get { return _request; }
    }

    class MockHttpRequest : HttpRequestBase
    {
        readonly HttpCookieCollection _cookies;

        public MockHttpRequest()
        {
            _cookies = new HttpCookieCollection();
        }

        public override HttpCookieCollection Cookies
        {
            get
            {
                return _cookies;
            }
        }
    }
}

Upvotes: 1

Related Questions