How to pass in a mocked HttpClient in a .NET test?

后端 未结 4 1774
不思量自难忘°
不思量自难忘° 2020-12-07 17:48

I have a service which uses Microsoft.Net.Http to retrieve some Json data. Great!

Of course, I don\'t want my unit test hitting the actual

4条回答
  •  情书的邮戳
    2020-12-07 18:16

    I know that this is an old question but I stumbled with it during a search on this topic and found a very nice solution to make testing HttpClient easier.

    It is available via nuget:

    https://github.com/richardszalay/mockhttp

    PM> Install-Package RichardSzalay.MockHttp
    

    Here is a quick look on the usage:

    var mockHttp = new MockHttpMessageHandler();
    
    // Setup a respond for the user api (including a wildcard in the URL)
    mockHttp.When("http://localost/api/user/*")
            .Respond("application/json", "{'name' : 'Test McGee'}"); // Respond with JSON
    
    // Inject the handler or client into your application code
    var client = new HttpClient(mockHttp);
    
    var response = await client.GetAsync("http://localost/api/user/1234");
    // or without await: var response = client.GetAsync("http://localost/api/user/1234").Result;
    
    var json = await response.Content.ReadAsStringAsync();
    
    // No network connection required
    Console.Write(json); // {'name' : 'Test McGee'}
    

    More info on the github project page. Hope this can be useful.

提交回复
热议问题