views:

201

answers:

2

Some of my controller actions need to respond with different ViewResults depending whether or not they were called by an AJAX request. Currently, I'm using the IsAjaxRequest() method to check for this. When this method is called during a unit test, it throws an ArgumentNullException because the HTTP context is missing.

Is there a way to mock/fake this call? Or is this a sign I should be checking for an AJAX request another way?

+7  A: 

Would it help if you provide a Test Double for the HTTP Context?

This can be done like this:

var httpCtxStub = new Mock<HttpContextBase>();

var controllerCtx = new ControllerContext();
controllerCtx.HttpContext = httpCtxStub.Object;

sut.ControllerContext = controllerCtx;

where sut represents the System Under Test (SUT), i.e. the Controller you wish to test.

This example uses Moq.

Mark Seemann
A: 

You can find an answer to your question on this page: Unit Testing Ajax Actions in ASP.Net MVC Controllers

If you are using a Test Helper frameworks such as MVCContrib, this post may help too.

Amin Emami