我有一个Microsoft.Net.Http
用于检索一些Json
数据的服务.大!
当然,我不希望我的单元测试击中实际的服务器(否则,这是一个集成测试).
这是我的服务ctor(使用依赖注入......)
public Foo(string name, HttpClient httpClient = null) { ... }
我不知道我怎么可以......比如嘲笑这个.. Moq
或FakeItEasy
.
我想确保当我的服务电话GetAsync
或PostAsync
..然后我可以伪造这些电话.
有什么建议我怎么做?
我希望 - 我不需要制作我自己的Wrapper ..因为这是废话:(微软不能对此进行疏忽,对吧?
(是的,它很容易制作包装..我之前已经完成了它们......但这是重点!)
您可以用假的核心HttpMessageHandler替换它.看起来像这样......
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}; } } }
然后你可以创建一个使用假处理程序的客户端.
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);
我知道这是一个老问题,但我在搜索这个主题时偶然发现了它,并找到了一个非常好的解决方案,使测试HttpClient
更容易.
它可以通过nuget获得:
https://github.com/richardszalay/mockhttp
PM> Install-Package RichardSzalay.MockHttp
以下是对使用情况的快速了解:
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'}
有关github项目页面的更多信息.希望这可能有用.