1

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?

1
  • 2
    Abstract HttpClient away. in tests IoC will replace that class with a controlled mock. Well you may also split action in one *Impl method, if you do not need to test HttpClient related code Commented Feb 20, 2015 at 18:28

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.