0

我正在尝试在 C# 中测试 VS 2017 中的适配器服务。我的测试失败了,因为它需要 400 到 499 的响应HTTPClient。当我的测试运行时,服务返回 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)
4

1 回答 1

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;

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

于 2019-01-04T21:30:00.463 回答