如何在.NET测试中嘲笑HttpClient的通行证? [英] How to pass in a mocked HttpClient in a .NET test?

查看:203
本文介绍了如何在.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)
{
...
}

我不知道我怎么可以......这嘲笑说.. 起订量 FakeItEasy

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

我要确保当我的服务呼叫 GetAsync PostAsync ..然后我可以伪造这些电话。

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

任何建议,我该怎么办呢?

Any suggestions how I can do that?

我米-hoping-我并不需要使自己的包装..导致这就是废话:(微软无法做出这一疏忽,对吧?

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 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 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的通行证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆