我有一个使用Microsoft.Net.Http
来检索一些Json
数据的服务。太棒了!
当然,我不希望我的单元测试命中实际的服务器(否则,这是一个集成测试)。
下面是我的服务ctor (它使用依赖注入...)
public Foo(string name, HttpClient httpClient = null)
{
...
}
我不知道我怎么能用..。比方说..Moq
或FakeItEasy
。
我希望确保当我的服务调用GetAsync
或PostAsync
时..然后我就可以伪造那些电话了。
有什么建议可以让我这样做吗?
我希望我不需要自己做包装纸..因为那是废话:(微软不可能对此进行疏忽,对吧?
(是的,制作包装纸很容易。我以前做过..。但这就是重点!)
发布于 2014-03-08 03:09:54
您可以将核心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 override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
if (_FakeResponses.ContainsKey(request.RequestUri))
{
return Task.FromResult(_FakeResponses[request.RequestUri]);
}
else
{
return Task.FromResult(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);
发布于 2015-12-11 19:40:10
我知道这是一个古老的问题,但我在搜索这个话题时遇到了这个问题,并找到了一个非常好的解决方案,使测试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项目页面上有更多信息。希望这能对你有所帮助。
发布于 2014-03-06 11:53:44
您可能会看看Microsoft Fakes,特别是Shims
-section。使用它们,您可以修改HttpClient本身的行为。前提条件是,您使用的是VS Premium或Ultimate。
https://stackoverflow.com/questions/22223223
复制相似问题