3

I want to create Nunit test case for ASP.NET MVC application. If the ASP.NET uses Request.QueryString or Request.Url. then the unit test case will return null reference exception since the Request.querystring will return the value if the control comes from UI only.

So can you please help on this to create a unit test for MVC controller which uses Httpcontext.Request attributes.

1 Answer 1

4

Your unit test runs outside of the HttpContext and therefore you either need to mock the HttpContext or change your architecture to work around the problem, an example of this is shown below:

http://volaresystems.com/Blog/post/Dont-mock-HttpContext.aspx

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

11 Comments

Thank you for your update Burt. Can you please let me know the namespace to use the mock concepts?
Have a read at this article it will go into a lot more depth on the subject that I can: simple-talk.com/dotnet/asp.net/…
Hi Burt, Thanks for the update. My controller sample code is as below. public ActionResults index() { if(Request.Url.ToString()=="www.abc.com") { return RedirecttoAction("About"); } return View(); } Unit Test Code is as follows: [Test] public void testIndex(){ SampleController controller = new SampleController(); ActionResult result = controller.Index() as ViewResult;} When the control goes to Request.URL the null reference exception throws. Can you please let me know how to initialize the Request.URL or Request.QueryString values from unit test project?
You need to mock out the dependencies e.g. you shouldn't be calling Request.Anything from code under test. If you put that code behind an interface you could mock the call and give whatever return result you want to enable you to test your code.
Hi Burt, Thanks for your help. Can you please give me the example for mock with interface?
|

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.