所以,让我首先说,我已经看到了创建包装器和模拟httpmethodrequest之间的战争中的所有线程。在过去,我已经非常成功地完成了包装方法,但是我认为我会沿着模仿httpmessagerequest的道路前进。
首先,这里是
辩论
:
Mocking HttpClient in unit tests
. 我想补充一点,这不是问题所在。
我发现我对注入httpclient的测试进行了测试。我做了很多无服务器的AWS lambda,基本流程如下:
//some pseudo code
public class Functions
{
public Functions(HttpClient client)
{
_httpClient = client;
}
public async Task<APIGatewayResponse> GetData(ApiGatewayRequest request, ILambdaContext context)
{
var result = await _client.Get("http://example.com");
return new APIGatewayResponse
{
StatusCode = result.StatusCode,
Body = await result.Content.ReadStringAsAsync()
};
}
}
...
[Fact]
public void ShouldDoCall()
{
var requestUri = new Uri("http://example.com");
var mockResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(expectedResponse) };
var mockHandler = new Mock<HttpClientHandler>();
mockHandler
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
It.IsAny<HttpRequestMessage>(),
It.IsAny<CancellationToken>())
.ReturnsAsync(mockResponse);
var f = new Functions(new HttpClient(handler.Object);
var result = f.GetData().Result;
handlerMock.Protected().Verify(
"SendAsync",
Times.Exactly(1), // we expected a single external request
ItExpr.Is<HttpRequestMessage>(req =>
req.Method == HttpMethod.Get &&
req.RequestUri == expectedUri // to this uri
),
ItExpr.IsAny<CancellationToken>()
);
Assert.Equal(200, result.StatusCode);
}
所以这就是我的问题所在!
当我所有的测试都运行时
NCrunch
他们过了,而且过得很快!
当我手动运行它们时
Resharper 2018
他们失败了。
同样,当它们在ci/cd平台(Linux发行版上带有net core 2.1sdk的Docker容器)内运行时,它们也会失败。
这些测试不应该并行运行(以这种方式读取测试的默认值)。我对这些方法进行了大约30个测试,每一个都在moq检验部分随机失败。
有时他们通过,有时他们失败。
如果我以这种方式分解每个测试类和运行组时的测试,而不是一个测试类中的所有测试,那么这些测试都将以块的形式通过。我还要补充一点,我甚至尝试过分离每个测试方法的变量,以确保没有重叠。
所以,我真的对通过这里来处理这件事感到迷茫,并确保这是可测试的。
有不同的方法接近
HttpClient
它能一直通过哪里?