c# - How to pass in a mocked HttpClient in a .NET test? -
i have service uses microsoft.net.http
retrieve json
data. great!
of course, don't want unit test hitting actual server (otherwise, that's integration test).
here's service ctor (which uses dependency injection...)
public foo(string name, httpclient httpclient = null) { ... }
i'm not sure how can mock ... .. moq
or fakeiteasy
.
i want make sure when service calls getasync
or postasync
.. can fake calls.
any suggestions how can that?
i'm -hoping- don't need make own wrapper .. cause that's crap :( microsoft can't have made oversight this, right?
(yes, it's easy make wrappers .. i've done them before ... it's point!)
you can replace core httpmessagehandler fake one. looks this...
public class fakeresponsehandler : delegatinghandler { private readonly dictionary<uri, httpresponsemessage> _fakeresponses = new dictionary<uri, httpresponsemessage>(); public void addfakeresponse(uri uri, httpresponsemessage responsemessage) { _fakeresponses.add(uri,responsemessage); } protected async override task<httpresponsemessage> sendasync(httprequestmessage request, system.threading.cancellationtoken cancellationtoken) { if (_fakeresponses.containskey(request.requesturi)) { return _fakeresponses[request.requesturi]; } else { return new httpresponsemessage(httpstatuscode.notfound) { requestmessage = request}; } } }
and can create client use fake handler.
var fakeresponsehandler = new fakeresponsehandler(); fakeresponsehandler.addfakeresponse(new uri("http://example.org/test"), new httpresponsemessage(httpstatuscode.ok)); var httpclient = new httpclient(fakeresponsehandler); var response1 = await httpclient.getasync("http://example.org/notthere"); var response2 = await httpclient.getasync("http://example.org/test"); assert.equal(response1.statuscode,httpstatuscode.notfound); assert.equal(response2.statuscode, httpstatuscode.ok);
Comments
Post a Comment