Quantcast
Channel: User Pure.Krome - Stack Overflow
Viewing all articles
Browse latest Browse all 74

How can I use FakeItEasy with HttpClient, in a unit test?

$
0
0

I'm trying to figure out how to use FakeItEasy with the HttpClient, given the following code:

public Foo(string key, HttpClient httpClient = null){ .. }public void DoGet(){    ....    if (_httpClient == null)    {        _httpClient = new HttpClient();    }    var response = _httpClient.GetAsync("user/1);}public void DoPost(foo Foo){    if (_httpClient == null)    {        _httpClient = new HttpClient();    }    var formData = new Dictionary<string, string>    {        {"Name", "Joe smith"},        {"Age", "40"}    };        var response = _httpClient.PostAsync("user",         new FormUrlEncodedContent(formData));}

So I'm not sure how to use FakeItEasy, to fake out the HttpClient's GetAsync and PostAsync methods.

Production code will not pass in the HttpClient, but the unit test will pass in the fake instance, made by FakeItEasy.

eg.

[Fact]public void GivenBlah_DoGet_DoesSomething(){    // Arrange.    var httpClient A.Fake<HttpClient>(); // <-- need help here.    var foo = new Foo("aa", httpClient);    // Act.    foo.DoGet();    // Assert....}

Update

I grok that FiE (and most mocking packages) works on interfaces or virtual methods. So for this question, let's just prentend that the GetAsync and PostAsync methods are virtual.


Viewing all articles
Browse latest Browse all 74

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>