Michael Michael - 3 years ago 161
C# Question

Unit test AjaxRequest C#

[Test]
public void DetailPromocodeStatusWithModel()
{
var sut = _testContext.Sut;
_httpModelFactory.FakeHttpContext();
var mockHttpContext = MockRepository.GenerateMock<HttpContextBase>();
var mockRequest = MockRepository.GenerateMock<HttpRequestBase>();
mockHttpContext.Stub(x => x.Request).Return(mockRequest);
mockRequest.Stub(x => x.HttpMethod).Return("POST");
var context = new ControllerContext(mockHttpContext,new RouteData(),sut);
sut.ControllerContext = context;


var viewResult = sut.Enquire(SampleEnquiryForm());

Debug.Assert(viewResult != null, "view != null");
Assert.NotNull(viewResult);
}


*I am unit testing a class that has a particular IF statement that that requires my request to be a POST and isAjaxRequest to be true to get into a particular block. I have set up the POST part but I can't seem to set the headers to make it an AJAX request, without it failing. *

Answer Source

For unit-test you can mock isAjaxRequest() method to get into needed block. Personally, I use Typemock Isolator for such purposes, since it allows to mock static methods. Take a look:

[TestMethod, Isolated]
public void TestIsAjaxRequest()
{
    var fake = Isolate.Fake.Instance<HttpRequestBase>();

    Isolate.WhenCalled(() => AjaxRequestExtensions.IsAjaxRequest(null)).WillReturn(true);

    Assert.IsTrue(AjaxRequestExtensions.IsAjaxRequest(fake));
}

Hope it'll be helpful.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download