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

 wing96333 发布于 2023-01-19 16:55

我有一个Microsoft.Net.Http用于检索一些Json数据的服务.大!

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

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

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

我不知道我怎么可以......比如嘲笑这个.. MoqFakeItEasy.

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

有什么建议我怎么做?

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

(是的,它很容易制作包装..我之前已经完成了它们......但这是重点!)

2 个回答
  • 您可以用假的核心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 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};
                }
    
            }
        }
    

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

    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);
    

    2023-01-19 16:57 回答
  • 我知道这是一个老问题,但我在搜索这个主题时偶然发现了它,并找到了一个非常好的解决方案,使测试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项目页面的更多信息.希望这可能有用.

    2023-01-19 16:57 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有