If you don't want to create s specific derivation of HttpMessageHandler for each test, you can also have Moq create the mocks for you automagically. Instead, you mock HttpMessageHandler, put that into an HttpClient, and have it return whatever you want that way. & req.RequestUri = expectedUri // to this uriįor unit tests, you don't mock HttpClient. Req.Method = HttpMethod.Get // we expected a GET request ![]() Times.Exactly(1), // we expected a single external request also check the 'http' call was like we expected it Result.Should().NotBeNull() // this is fluent assertions here. GetSomethingRemoteAsync('api/test/whatever') Var subjectUnderTest = new MyTestClass(httpClient) Var httpClient = new HttpClient(handlerMock.Object) use real http client with mocked handler here This implementation could be as simple as this line: return Task.FromResult(new HttpResponseMessage() ]"), You create a class, derive it from HttpMessageHandler, implement SendAsync to return whatever HttpResponseMessage you want the HttpClient to return, and you are done. Using this, you can easily modify the behaviour of the HttpClient during your tests. This class is easy to mock too, as it only has a single method to implement: protected abstract Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken). The HttpClient has a constructor overload that takes an instance of the abstract class HttpMessageHandler, and this is the class does the actual heavy lifting within the HttpClient. The solution: Replace the HttpMessageHandler within HttpClient Instead, you replace the inner workings of the HttpClient for your tests. This means, you really don't mock HttpClient. That is also discussed in a lengthy thread on the CoreFx repo itself. It turned out that the approach to mock HttpClient isn't the way to go. So I did some reading, looked at things and thought about the whole situation from some different point of views. And when something constantly gets in my way like this did, I like to think about whether it might be my way that's problematic. It is more likely that a HttpClientFactory controls it, and you don't see a way to extend it so that it instanciates your wrapper type instead.īack to square one it is. And then you might think about how the HttpClient gets injected in your class in the first place, as you have to swap out this injection against your wrapper type.Īnd then it strikes you again: You usually don't control the HttpClient lifetime directly. While this could technically work, your will notice that HttpClient has a lot of methods you'd need to bridge over to the real implementation. The next idea you could come up with is to wrap the HttpClient in another class (aka Decorator pattern), and mock this out.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |