Unit Test ASP.NET Web Api IHttpActionResult

by sunil ravulapalli /13. November 2013 05:57 /asp.net-web-api /Comments (0)

Suppose the web api action looks like this

public IHttpActionResult Get(long accountId) 
{ 
       var payOffQuoteStatus = _payOffQuoteService.GetPayOffQuote(accountId); 

       return Ok<PayOffQuote>(payOffQuoteStatus.PayOffQuote); 
}

then the test would look like this

            //Arrange
            var payOffQuoteServiceMock = new Mock<IPayOffQuoteService>();
            payOffQuoteServiceMock.Setup(poqs => poqs.GetPayOffQuote(It.IsAny<long>()))
                                  .Returns(new PayOffQuoteStatus
                                      {
                                          IsEligibleForPayOffQuote = true,
                                          PayOffQuote = new PayOffQuote {BalanceOutstanding = 14225.68m}
                                      });
            var payOffController = new PayoffQuoteController(payOffQuoteServiceMock.Object);
            payOffController.Request = new HttpRequestMessage();
            payOffController.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());
            
            //Act
            var httpActionResult = payOffController.Get(12345678);

            //Assert
            OkNegotiatedContentResult<PayOffQuote> contentResult = httpActionResult as OkNegotiatedContentResult<PayOffQuote>;
            Assert.IsNotNull(contentResult);

            var payOffQuote = contentResult.Content as PayOffQuote;
            Assert.IsNotNull(payOffQuote);
            Assert.AreEqual(14225.68m, payOffQuote.BalanceOutstanding);
blog comments powered by Disqus