我正在使用
WebApplicationFactory
进行端到端测试,并且需要让我的测试主机应用程序取消注册以下内容
services.AddHttpClient<ISendGridClient, SendGridClient>();
然后我会像这样重新注册
services
.AddHttpClient<ISendGridClient, SendGridClient>()
.ConfigurePrimaryHttpMessageHandler(_ => MockSendGridHttpMessageHandler);
谁能告诉我如何注销之前添加的服务
.AddHttpClient<ISendGridClient, SendGridClient>()
?
要在使用
HttpClient
时覆盖测试运行期间的 WebApplicationFactory
行为,您需要修改 ConfigureTestServices
方法内的服务。
您可以在为特定测试的 API 初始化客户端时执行此操作。
var client = _factory.WithWebHostBuilder(builder =>
builder.ConfigureTestServices(
services =>
{
services
.AddHttpClient<ISendGridClient, SendGridClient>()
.ConfigurePrimaryHttpMessageHandler(() => new MockSendGridHttpMessageHandler());
})).CreateClient();
或者您可以实现自定义
WebApplicationFactory
以在一个位置应用更改,然后在需要特定行为的测试类中使用此实现。
namespace DropoutCoder.HttpClientHandlerReplacement.Tests
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using System.Net;
internal class ApiApplicationFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
builder.ConfigureTestServices(services =>
{
services.ConfigureHttpClientDefaults(builder =>
{
builder.ConfigurePrimaryHttpMessageHandler(() => new MockSendGridHttpMessageHandler());
});
});
}
}
}
请注意,使用
ConfigureHttpClientDefaults
方法配置默认客户端将覆盖通过 AddHttpClient
注册的每个 HttpClient。
我已经使用默认、命名和键入的
HttClient
注册创建了完整示例,您可以在 GitHub 上的 dropoutcoder/webapplicationfactory-httpclienthandler-replacement 存储库 中找到。