vendredi 20 février 2015

How to unit test MVC controller action that is using HttpClient

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?


Aucun commentaire:

Enregistrer un commentaire