1

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?

1
  • Did you ever solved this problem? I just had the same issue Commented Jan 8, 2012 at 1:50

1 Answer 1

4

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

You shouldn't be doing this and such controller shouldn't exist. The controller context is not yet initialized in the constructor and it will fail not only for the unit test but in real.

You should use the Initialize method where you have access to the request context.

Sign up to request clarification or add additional context in comments.

1 Comment

Why isn't this marked as the answer? I had a similar issue where I needed to access the request context, and this solution was better than I hoped for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.