NUll exception in filling a querystring by mocing framework

Posted by user564101 on Stack Overflow See other posts from Stack Overflow or by user564101
Published on 2011-01-06T07:51:07Z Indexed on 2011/01/06 7:53 UTC
Read the original article Hit count: 159

There is a simple controller that a querystring is read in constructor of it.

 public class ProductController : Controller
 {
    parivate string productName;

    public ProductController()
    {
       productName = Request.QueryString["productname"];
    }

    public ActionResult Index()
    {
        ViewData["Message"] = productName;

        return View();
    }
 }

Also I have a function in unit test that create an instance of this Controller and I fill the querystring by a Mock object like below.

[TestClass]
public class ProductControllerTest
{
    [TestMethod]
    public void test()
    {
        // Arrange 
        var querystring = new System.Collections.Specialized.NameValueCollection { { "productname", "sampleproduct"} };
        var mock = new Mock<ControllerContext>();
        mock.SetupGet(p => p.HttpContext.Request.QueryString).Returns(querystring);

        var controller = new ProductController();
        controller.ControllerContext = mock.Object;

        // Act
        var result = controller.Index() as ViewResult;


        // Assert
        Assert.AreEqual("Index", result.ViewName);
    }
}

Unfortunately Request.QueryString["productname"] is null in constructor of ProductController when I run test unit.

Is ther any way to fill a querystrin by a mocking and get it in constructor of a control?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about unit-testing