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

How to pass in a mocked HttpClient in a .NET test?(如何在 .NET 测试中传入模拟的 HttpClient?)
本文介绍了如何在 .NET 测试中传入模拟的 HttpClient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个服务,它使用 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)
How to store delegates in a List(如何将代表存储在列表中)
How delegates work (in the background)?(代表如何工作(在后台)?)
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)