c# - 在 VS 2017 中使用 MockHttpClient nuget 包

标签 c# testing mocking

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

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

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

我得到一个错误提示

'MockHttpClient' is a namespace but is used like a type

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

我做错了什么?

出现以下错误

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

最佳答案

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

删除 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;

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

关于c# - 在 VS 2017 中使用 MockHttpClient nuget 包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54046009/

相关文章:

symfony - 如何用phpunit模拟依赖注入(inject)?

java - 使用 JMockit 模拟被测类的私有(private)方法

c# - 程序启动时自动调试

ruby-on-rails - Rails 应用程序需要每月执行一次任务

c# - 如何在 StepArgumentTransformation 中使用 REGEX 查找带前缀的字符串

java - Camel : Ignore some messages in mock endpoint

c# - 为什么 SByte 和 Int32 CompareTo() 方法的行为不同?

c# - 多项目模板 Visual Studio 2017

c# - Visual Studio 2013 项目引用另一个带有外部库的项目

testing - 在 qtp 中找不到与请求的名称或序号对应的集合中的项目