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

编程入门 行业动态 更新时间:2024-10-24 01:55:53
本文介绍了如何在 .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) { ... }

我不知道如何用......说.. Moq 或 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.

有什么建议吗?

我-希望-我不需要制作自己的 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("example/test"), new HttpResponseMessage(HttpStatusCode.OK)); var httpClient = new HttpClient(fakeResponseHandler); var response1 = await httpClient.GetAsync("example/notthere"); var response2 = await httpClient.GetAsync("example/test"); Assert.Equal(response1.StatusCode,HttpStatusCode.NotFound); Assert.Equal(response2.StatusCode, HttpStatusCode.OK);

更多推荐

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

本文发布于:2023-10-31 07:43:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545469.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   测试中   NET   HttpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!