如何在 .NET 测试中传入模拟的 HttpClient?

时间:2023-05-06
本文介绍了如何在 .NET 测试中传入模拟的 HttpClient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个服务,它使用 Microsoft.Net.Http 来检索一些 Json 数据.太好了!

I have a service which uses Microsoft.Net.Http to retrieve some Json data. Great!

当然,我不希望我的单元测试到达实际的服务器(否则,这是一个集成测试).

Of course, I don't want my unit test hitting the actual server (otherwise, that's an integration test).

这是我的服务 ctor(使用依赖注入...)

Here's my service ctor (which uses dependency injection...)

public Foo(string name, HttpClient httpClient = null)
{
...
}

我不知道如何用......说.. MoqFakeItEasy 来模拟它.

I'm not sure how I can mock this with ... say .. Moq or FakeItEasy.

我想确保当我的服务调用 GetAsyncPostAsync .. 然后我可以伪造这些调用.

I want to make sure that when my service calls GetAsync or PostAsync .. then i can fake those calls.

有什么建议吗?

我-希望-我不需要制作自己的 Wrapper .. 因为那是废话 :( 微软不可能对此进行疏忽,对吧?

I'm -hoping- i don't need to make my own Wrapper .. cause that's crap :( Microsoft can't have made an oversight with this, right?

(是的,制作包装很容易......我以前做过......但这就是重点!)

(yes, it's easy to make wrappers .. i've done them before ... but it's the point!)

推荐答案

你可以用一个假的 HttpMessageHandler 替换核心.看起来像这样的东西......

You can replace the core HttpMessageHandler with a fake one. Something that looks like 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 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 });
        }
    }
}

然后您可以创建一个将使用假处理程序的客户端.

and then you can create a client that will use the 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);

这篇关于如何在 .NET 测试中传入模拟的 HttpClient?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:为什么使用 It.is&lt;&gt;或It.IsAny&lt;& 下一篇:在 Moq Callback() 调用中设置变量值

相关文章

最新文章