Unit test class that uses HttpClient in System.Net.Http v4

I want to unit test the following search class that uses HttpClient,

public class Search:ISearch{ HttpClient httpClient; public Search(HttpClient httpClient){ this.httpClient = httpClient; } //use httClient to send request. } 

Is there any way to make fun of HttpClient? I can not find information through Google.

Update

Is there an alternative to sending an Http web request that can be ridiculed. I have the code below:

  public class Search:ISearch{ private static readonly string url = "http://www.google.com/search"; public Result SendSearch(string query){ string queryUrl = string.Format("{0}?q={1}", url, query); var webRequest = WebRequest.Create(queryUrl); ///... } 
+4
source share
2 answers

You cannot mock this with a mocking structure like Rhino-Mocks, because for this you need either interface or virtual methods in the HttpClient class. The mocking structure will create a layout for you that either implements the methods defined on the interface or overrides the methods of your virtual class.

So, either you end the HttpClient class, and let it implement the interface, or don’t mock it.

If you change the code to something like this:

 public class Search:ISearch { private static readonly string url = "http://www.google.com/search"; private readonly IWebRequestCreator _generator; public Search(IWebRequestCreator generator) { _generator = generator; } public Result SendSearch(string query) { var queryUrl = string.Format("{0}?q={1}", url, query); var webRequest = _generator.Create(queryUrl); // ... } } 

If you create a class that implements IWebRequestCreator , then you can mock functionality. The implementation class will simply call WebRequest.Create(queryUrl);

+2
source

In the .NET Framework you can do this.

 public class FakeHttpMessageHandler : HttpMessageHandler { private HttpResponseMessage response; public FakeHttpMessageHandler(HttpResponseMessage response) { this.response = response; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var responseTask = new TaskCompletionSource<HttpResponseMessage>(); responseTask.SetResult(response); return responseTask.Task; } } [TestMethod] public void TestGetContents() { var responseMessage = new HttpResponseMessage(); var messageHandler = new FakeHttpMessageHandler(responseMessage); var client = new HttpClient(messageHandler); var sut = new Search(client); sut.SendSearch("urQuery"); // Asserts } 
+3
source

All Articles