[RESOLVED]Mock Response.Cookies.Add(…) in MVC unit testing

The basic problem is that the controller I’m testing calls Response.Cookies.Add(…) but since the unit test is not in an HTTPContext, Response is null and I get an exception. Can someone give me an example. ?

Look at hanselmann 

http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx

how it mocks Request and Request.Files

Same way you will mock Request and Request.Cookies

You have to abstract access to non-testable resources like cookies.  Create an interface and a class that implements your interface

namespace TestMvc.Managers
{
    public interface IClientStorageManager
    {
        void Store(string key, string value);
    }
}

namespace TestMvc.Managers
{
    public class CookieStorageManager : IClientStorageManager
    {
        public void Store(string key, string value)
        {
            HttpCookie c = new HttpCookie(key);
            c.Value = value;

            System.Web.HttpContext.Current.Response.Cookies.Add(c);
        }
    }
}

Use this rather than accessing cookies direct

public class HomeController : Controller
{
    private IClientStorageManager clientStorageManager;

    public HomeController()
        : this(new CookieStorageManager())
    {
        // you can use DI to do this instead
    }

    public HomeController(IClientStorageManager clientStorageManager)
    {
        this.clientStorageManager = clientStorageManager;
    }

    public ActionResult Index(string name = null)
    {
        this.clientStorageManager.Store("name", name);

        return View();
    }

You can now mock the storage class from your unit test

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        // I'm using moq, but you can use any mocking framework you want, or even self-shunting
        Mock<IClientStorageManager> storage = new Mock<IClientStorageManager>();

        HomeController c = new HomeController(storage.Object);

        c.Index("Bob");

        storage.Verify(s => s.Store(It.IsAny<string>(), "Bob"), Times.AtLeastOnce());
    }
}

Leave a Reply