我喜欢对使用<%= f.fields_for :questions do |builder| %>
的类进行单元测试。我们在类构造函数中注入了_question_fields.html.erb
对象。
HttpClient
现在我们想对HttpClient
方法进行单元测试。我们使用public class ClassA : IClassA
{
private readonly HttpClient _httpClient;
public ClassA(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<HttpResponseMessage> SendRequest(SomeObject someObject)
{
//Do some stuff
var request = new HttpRequestMessage(HttpMethod.Post, "http://some-domain.in");
//Build the request
var response = await _httpClient.SendAsync(request);
return response;
}
}
进行单元测试框架,使用ClassA.SendRequest
进行模拟。
当我们尝试模仿Ms Test
时,它会抛出Moq
。
HttpClient
我们如何解决这个问题?
答案 0 :(得分:10)
特定的重载方法不是虚拟的,因此无法被Moq覆盖。
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request);
这就是它抛出NotSupportedException
您正在寻找的虚拟方法是此方法
public virtual Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken);
然而,模拟HttpClient
并不像内部消息处理程序那样简单。
我建议使用具有自定义消息处理程序存根的具体客户端,以便在伪造请求时提供更大的灵活性。
以下是委托处理程序存根的示例。
public class DelegatingHandlerStub : DelegatingHandler {
private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _handlerFunc;
public DelegatingHandlerStub() {
_handlerFunc = (request, cancellationToken) => Task.FromResult(request.CreateResponse(HttpStatusCode.OK));
}
public DelegatingHandlerStub(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handlerFunc) {
_handlerFunc = handlerFunc;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
return _handlerFunc(request, cancellationToken);
}
}
注意默认构造函数基本上是在做你之前尝试模拟的东西。它还允许使用委托代理的更多自定义方案。
使用存根,测试可以重构为类似
public async Task _SendRequestAsync_Test() {
//Arrange
var handlerStub = new DelegatingHandlerStub();
var client = new HttpClient(handlerStub);
var sut = new ClassA(client);
var obj = new SomeObject() {
//Populate
};
//Act
var response = await sut.SendRequest(obj);
//Assert
Assert.IsNotNull(response);
Assert.IsTrue(response.IsSuccessStatusCode);
}
答案 1 :(得分:4)
使用HttpClient进行模拟是很难的,因为它是在大多数人在dotnet中进行单元测试之前编写的。有时我会设置一个存根HTTP服务器,它根据与请求URL匹配的模式返回预设响应,这意味着您测试真实的HTTP请求而不是模拟,而是测试本地主机服务器。使用WireMock.net使这非常简单并且运行速度足以满足我的大部分单元测试需求。
因此,代替http://some-domain.in
在某个端口上使用localhost服务器设置,然后:
var server = FluentMockServer.Start(/*server and port can be setup here*/);
server.Given(
Request.Create()
.WithPath("/").UsingPost()
)
.RespondWith(
Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithBody("{'attr':'value'}")
);
答案 2 :(得分:2)
Moq可以模拟出受保护的方法,例如HttpMessageHandler上的SendAsync,您可以在其构造函数中提供给HttpClient。
var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
mockHttpMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK
});
var client = new HttpClient(mockHttpMessageHandler.Object);
从https://thecodebuzz.com/unit-test-mock-httpclientfactory-moq-net-core/复制
答案 3 :(得分:1)
我最近不得不模拟 HttpClient,我使用了 Moq.Contrib.HttpClient。这是我需要的,而且使用起来很简单,所以我想我会把它扔在那里。
以下是一般用法的示例:
// All requests made with HttpClient go through its handler's SendAsync() which we mock
var handler = new Mock<HttpMessageHandler>();
var client = handler.CreateClient();
// A simple example that returns 404 for any request
handler.SetupAnyRequest()
.ReturnsResponse(HttpStatusCode.NotFound);
// Match GET requests to an endpoint that returns json (defaults to 200 OK)
handler.SetupRequest(HttpMethod.Get, "https://example.com/api/stuff")
.ReturnsResponse(JsonConvert.SerializeObject(model), "application/json");
// Setting additional headers on the response using the optional configure action
handler.SetupRequest("https://example.com/api/stuff")
.ReturnsResponse(bytes, configure: response =>
{
response.Content.Headers.LastModified = new DateTime(2018, 3, 9);
})
.Verifiable(); // Naturally we can use Moq methods as well
// Verify methods are provided matching the setup helpers
handler.VerifyAnyRequest(Times.Exactly(3));
有关详细信息,请查看作者的博文 here。