【问题标题】:Using MockHttpClient nuget package in VS 2017在 VS 2017 中使用 MockHttpClient nuget 包
【发布时间】:2019-01-04 21:02:08
【问题描述】:

我正在尝试在 C# 中测试 VS 2017 中的适配器服务。我的测试失败了,因为它需要来自HTTPClient 的 400 到 499 响应。当我的测试运行时,服务返回 500。

所以搜索我找到了 MockHttpClient nuget 包,但是当我在测试中尝试它们时,给出的示例不起作用。

示例: https://github.com/codecutout/MockHttpClient/blob/master/README.md

我收到一个错误提示

'MockHttpClient' 是一个命名空间,但用作类型

我还在测试顶部添加了using MockHTTPClient

我做错了什么?

出现以下错误

var mockHttpClient = new MockHttpClient();
mockHttpClient.When("the url I am using").Returns(HttpStatusCode.Forbidden)

【问题讨论】:

  • 如果 using 命名空间导致问题,请尝试使用命名空间和类的 new MockHttpClient.MockHttpClient()。我认为该库的命名约定很差
  • @Nkosi,谢谢你的工作。你会推荐另一个 nuget 包来满足我在开发代码中调用它时在我的测试中模拟 HTTPClient 响应吗?

标签: c# testing mocking


【解决方案1】:

这是与命名空间的名称冲突。类和命名空间共享相同的名称。

删除using 语句并改用它:

var mockHttpClient = new MockHttpClient.MockHttpClient();

此库的名称选择不当,并且依赖项数量惊人。如果我是你,我会远离。

更新:

你要求一个替代方案,所以这是我最近为一个项目所做的:

HttpClient 类有一个接受HttpMessageHandler 对象的构造函数,因此您可以传递自己的处理程序并模拟行为。

创建一个派生自DelegatingHandler 并覆盖发送行为的类:

public class TestHandler : DelegatingHandler
{
    private Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _handler;

    public TestHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handler)
    {
        _handler = handler;
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return _handler(request, cancellationToken);
    }

    public static Task<HttpResponseMessage> OK()
    {
        return Task.Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.OK));
    }

    public static Task<HttpResponseMessage> BadRequest()
    {
        return Task.Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.BadRequest));
    }
}

然后在您的测试中,您在构造函数中使用您的处理程序:

//Create an instance of the test handler that returns a bad request response
var testHandler = new TestHandler((r, c) =>
{                
    return TestHandler.BadRequest();
});

//Create the HTTP client
var client = new HttpClient(testHandler);

//Fake call, will never reach out to foo.com
var request = new HttpRequestMessage(HttpMethod.Get, "http://www.foo.com");
request.Content = new StringContent("test");

//This will call the test handler and return a bad request response
var response = client.SendAsync(request).Result;

请注意,我有几个方便的静态方法可以为我创建处理函数。

【讨论】:

  • 谢谢@JuanR 你会推荐什么?
  • 所以我实际上是从这条路开始的,由于我是自动化测试的新手,所以我以有限的知识开始搜索我发布的 nuget 包。因此,如果我正在测试的代码在我正在测试的方法中创建客户端对象,那么您在上面发布的更新将起作用。我没有直接测试 HTTPClient。如果状态码为 401 则返回开发团队设置的一般错误。希望这是有道理的...我正在测试其中包含 HTTPClient 代码的服务。
  • @rowdog_14:在这种情况下,您需要能够注入HttpClient 对象。这样你就可以配置它来做你想做的事。如果它是一项服务,您可能希望有一个构造函数重载,将其作为参数或类似的东西。
猜你喜欢
  • 2017-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多