我在模拟Azure函数中的IHttpClientFactory接口时遇到了一些问题。下面是我正在做的事情,我有触发器,一旦收到消息,我正在调用API来更新数据。为此,我使用了SendAsync方法。在编写单元测试用例时,我无法模拟client.For测试,我尝试在构造函数本身中进行get调用,但仍然不起作用。函数类
public class UpdateDB
{
private readonly IHttpClientFactory _clientFactory;
private readonly HttpClient _client;
public UpdateDB(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
_client = clientFactory.CreateClient();
_client.GetAsync("");
}
[FunctionName("DB Update")]
public async Task Run([ServiceBusTrigger("topic", "dbupdate", Connection = "connection")]string mySbMsg, ILogger log)
{
var client = _clientFactory.CreateClient();
log.LogInformation($"C# ServiceBus topic trigger function processed message: {mySbMsg}");
DBConvert payload = JsonConvert.DeserializeObject<DBConvert>(mySbMsg);
string jsonContent = JsonConvert.SerializeObject(payload);
var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, "api/DBU/data");
message.Content = httpContent;
var response = await client.SendAsync(message);
}
}TestClass
namespace XUnitTestProject1
{
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 class test
{
[Fact]
public async Task Should_Return_Ok()
{
//
Mock<ILogger> _logger = new Mock<ILogger>();
var expected = "Hello World";
var mockFactory = new Mock<IHttpClientFactory>();
var configuration = new HttpConfiguration();
var clientHandlerStub = new DelegatingHandlerStub((request, cancellationToken) =>
{
request.SetConfiguration(configuration);
var response = request.CreateResponse(HttpStatusCode.Accepted);
return Task.FromResult(response);
});
var client = new HttpClient(clientHandlerStub);
mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(client);
var clientTest = mockFactory.Object.CreateClient();
//Works Here, but not in the instance.
clientTest.GetAsync("");
IHttpClientFactory factory = mockFactory.Object;
var service = new UpdateDB(factory);
await service.Run("", _logger.Object);
}
}
}我已经遵循了这里的示例。How to mock the new HttpClientFactory in .NET Core 2.1 using Moq
发布于 2019-09-10 16:58:06
为了模拟/拦截HttpClient的使用,我建议您使用mockhttp,然后您的测试将是:
class Test {
private readonly Mock<IHttpClientFactory> httpClientFactory;
private readonly MockHttpMessageHandler handler;
constructor(){
this.handler = new MockHttpMessageHandler();
this.httpClientFactory = new Mock<IHttpClientFactory>();
this.httpClientFactory.Setup(_ => _.CreateClient(It.IsAny<string>()))
.Returns(handler.ToHttpClient());
}
[Fact]
public async Task Test(){
// Arrange
this.handler.Expect("api/DBU/data")
.Respond(HttpStatusCode.Ok);
var sut = this.CreateSut();
// Act
await sut.Run(...);
// Assert
this.handler.VerifyNoOutstandingExpectation();
}
private UpdateDB CreateSut() => new UpdateDB(this.httpClientFactory.Object);
}您可以进一步配置HTTP请求期望的行为方式,但为此,您应该阅读一点mockhttp文档
https://stackoverflow.com/questions/57866581
复制相似问题