有几种不同的方法来模拟HttpClient。以下是我在决定使用单一解决方案(Moq.Contrib.HttpClient)之前对xUnit做的一些POC。请注意,每个框架都有比下面所示更多的功能;为了清晰起见,我保持了每个例子的简洁。
最小起订量(自行决定)
如果您熟悉使用Moq框架,这是相对简单的。“诀窍”是在HttpClient内部模拟HttpMessageHandler——而不是HttpClient本身。注意:使用MockBehavior是一个很好的实践。严格模拟,以便提醒您没有显式模拟和预期的任何调用。
RichardSzalay。MockHttp
RichardSzalay。MockHttp是另一个流行的解决方案。我以前使用过这个,但发现它比Moq.Contrib.HttpClient稍微麻烦一些。这里可以使用两种不同的模式。Richard在这里描述了什么时候使用其中一个和另一个。
Moq.Contrib.HttpClient
就像使用Moq本身的解决方案一样,如果您熟悉使用Moq框架,这是很简单的。我发现这个解决方案更直接,代码更少。这是我选择使用的解决方案。注意,这个解决方案需要一个独立于Moq本身的Nuget - Moq. contrib . httpclient
WireMock。网
作为游戏的新手,WireMock.net越来越受欢迎。这将是一个合理的解决方案,而不是Microsoft.AspNetCore.TestHost,如果您正在编写集成测试,其中对端点的调用是实际执行的,而不是模拟的。一开始我以为这是我的选择,但出于两个原因决定放弃:
它实际上是开放端口以方便测试。由于我过去不得不修复由于HttpClient使用不当而导致的端口耗尽问题,所以我决定放弃这个解决方案,因为我不确定它在并行运行许多单元测试的大型代码库中是否能很好地扩展。
使用的url必须是可解析的(实际合法的url)。如果你想要简单的不关心一个“真正的”url(只是你期望的url实际上被调用),那么这可能不适合你。
例子
给定以下简单/做作的代码,下面是编写每个测试的方法。
public class ClassUnderTest
{
private readonly HttpClient _httpClient;
private const string Url = "https://myurl";
public ClassUnderTest(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<Person> GetPersonAsync(int id)
{
var response = await _httpClient.GetAsync($"{Url}?id={id}");
return await response.Content.ReadFromJsonAsync<Person>();
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
最小起订量(自行决定)
[Fact]
public async Task JustMoq()
{
//arrange
const int personId = 1;
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
var dto = new Person { Id = personId, Name = "Dave", Age = 42 };
var mockResponse = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = JsonContent.Create<Person>(dto)
};
mockHandler
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(m => m.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(mockResponse);
// Inject the handler or client into your application code
var httpClient = new HttpClient(mockHandler.Object);
var sut = new ClassUnderTest(httpClient);
//act
var actual = await sut.GetPersonAsync(personId);
//assert
Assert.NotNull(actual);
mockHandler.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(m => m.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>());
}
RichardSzalay。MockHttp(使用BackendDefinition模式)
[Fact]
public async Task RichardSzalayMockHttpUsingBackendDefinition()
{
//arrange
const int personId = 1;
using var mockHandler = new MockHttpMessageHandler();
var dto = new Person { Id = personId, Name = "Dave", Age = 42 };
var mockResponse = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = JsonContent.Create<Person>(dto)
};
var mockedRequest = mockHandler.When(HttpMethod.Get, "https://myurl?id=1")
.Respond(mockResponse.StatusCode, mockResponse.Content);
// Inject the handler or client into your application code
var httpClient = mockHandler.ToHttpClient();
var sut = new ClassUnderTest(httpClient);
//act
var actual = await sut.GetPersonAsync(personId);
//assert
Assert.NotNull(actual);
Assert.Equivalent(dto, actual);
Assert.Equal(1, mockHandler.GetMatchCount(mockedRequest));
mockHandler.VerifyNoOutstandingRequest();
}
RichardSzalay。MockHttp(使用RequestExpectation模式)
[Fact]
public async Task RichardSzalayMockHttpUsingRequestExpectation()
{
//arrange
const int personId = 1;
using var mockHandler = new MockHttpMessageHandler();
var dto = new Person { Id = personId, Name = "Dave", Age = 42 };
var mockResponse = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = JsonContent.Create<Person>(dto)
};
var mockedRequest = mockHandler.Expect(HttpMethod.Get, "https://myurl")
.WithExactQueryString($"id={personId}")
.Respond(mockResponse.StatusCode, mockResponse.Content);
// Inject the handler or client into your application code
var httpClient = mockHandler.ToHttpClient();
var sut = new ClassUnderTest(httpClient);
//act
var actual = await sut.GetPersonAsync(personId);
//assert
Assert.NotNull(actual);
Assert.Equivalent(dto, actual);
Assert.Equal(1, mockHandler.GetMatchCount(mockedRequest));
mockHandler.VerifyNoOutstandingExpectation();
}
Moq.Contrib.HttpClient
[Fact]
public async Task UsingMoqContribHttpClient()
{
//arrange
const int personId = 1;
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
var dto = new Person { Id = personId, Name = "Dave", Age = 42 };
var mockUrl = $"https://myurl?id={personId}";
var mockResponse = mockHandler.SetupRequest(HttpMethod.Get, mockUrl)
.ReturnsJsonResponse<Person>(HttpStatusCode.OK, dto);
// Inject the handler or client into your application code
var httpClient = mockHandler.CreateClient();
var sut = new ClassUnderTest(httpClient);
//act
var actual = await sut.GetPersonAsync(personId);
//assert
Assert.NotNull(actual);
Assert.Equivalent(dto, actual);
mockHandler.VerifyRequest(HttpMethod.Get, mockUrl, Times.Once());
}
WireMock。网
public class TestClass : IDisposable
{
private WireMockServer _server;
public TestClass()
{
_server = WireMockServer.Start();
}
public void Dispose()
{
_server.Stop();
}
[Fact]
public async Task UsingWireMock()
{
//arrange
const int personId = 1;
var dto = new Person { Id = personId, Name = "Dave", Age = 42 };
var mockUrl = $"https://myurl?id={personId}";
_server.Given(
Request.Create()
.WithPath("/"))
.RespondWith(
Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithBodyAsJson(dto));
// Inject the handler or client into your application code
var httpClient = _server.CreateClient();
var sut = new ClassUnderTest(httpClient);
//act
var actual = await sut.GetPersonAsync(personId);
//assert
Assert.NotNull(actual);
Assert.Equivalent(dto, actual);
}
}