当前位置 > 首页 > Asp.net

Writing Unit Tests for an ASP.NET MVC Action Method that handles Ajax Request and Normal Request

2012-12-9 16:13:00来源:Asp.net

In this blog post, I will demonstrate how to write unit tests for an ASP.NET MVC action method, which handles both Ajax request and normal HTTP Request. I will write a unit test for specifying the behavior of an Ajax request and will write another unit test for specifying the behavior of a normal HTTP request. Both Ajax request and normal request will be handled by a single action method. So the ASP.NET MVC action method will be execute HTTP Request object’s IsAjaxRequest method for identifying whether it is an Ajax request or not. So we have to create mock object for Request object and also have to make as a Ajax request from the unit test for verifying the behavior of an Ajax request. I have used NUnit and Moq for writing unit tests.

Let me write a unit test for a Ajax request

Code Snippet
  1. [Test]
  2. public void Index_AjaxRequest_Returns_Partial_With_Expense_List()
  3. {
  4. ????// Arrange??
  5. ????Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();
  6. ????Mock<HttpResponseBase> response = new Mock<HttpResponseBase>();
  7. ????Mock<HttpContextBase> context = new Mock<HttpContextBase>();
  8.  
  9. ????context.Setup(c => c.Request).Returns(request.Object);
  10. ????context.Setup(c => c.Response).Returns(response.Object);
  11. ????//Add XMLHttpRequest request header
  12. ????request.Setup(req => req["X-Requested-With"]).
  13. ????????Returns("XMLHttpRequest");
  14.  
  15. ????IEnumerable<Expense> fakeExpenses = GetMockExpenses();
  16. ????expenseRepository.Setup(x => x.GetMany(It.
  17. ????????IsAny<Expression<Func<Expense, bool>>>())).
  18. ????????Returns(fakeExpenses);
  19. ????ExpenseController controller = new