Reputation: 3364
I am trying to test the following MVC controller Action, which is calling out to Web API for a List of Products:
public ActionResult Index()
{
var model = new List<Product>();
using(HttpClient client = new HttpClient())
{
model = client.GetAsync(uri).Result.Content.ReadAsAsync<List<Product>>().Result;
}
return View(model);
}
I am trying to unit test this, have tried using Telerik JustMock to test, for example:
[TestMethod]
public void IndexDisplaysAllProducts()
{ // Not sure how to call here
var repo = Mock.Arrange(() => (new List<Product>())).Returns(
new List<Product> {
new Product(),
new Product(),
new Product()
});
var controller = new ProductsController();
var result = (ViewResult)controller.Index();
var model = (List<Product>)result.Model;
Assert.AreEqual(3, model.Count);
}
Just wondered how you would go about testing this?
Upvotes: 1
Views: 746
Reputation: 331
Mobile atm, so excuse brevity. Implement an httpclientfactory class and Ihttpclientfactory interface, inject that to the ctor using ioc then mock during test to create a mocked instance of the http client.
Alternatively, and even simpler to test, you could use this approach to implement a factory class for something that does all of the stuff you're using the http client for (GetAsync(uri).Result.Content.ReadAsAsync>() etc)
Hth
Upvotes: 2