Ibr*_*taz 8 c# integration-testing unit-testing asp.net-core asp.net-core-2.2
有谁知道是否可以WebApplicationFactory<TStartop>()在同一个单元测试中托管多个实例?
我已经尝试过,但似乎无法解决这个问题。
IE
_client = WebHost<Startup>.GetFactory().CreateClient();
var baseUri = PathString.FromUriComponent(_client.BaseAddress);
_url = baseUri.Value;
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer", "Y2E890F4-E9AE-468D-8294-6164C59B099Y");
Run Code Online (Sandbox Code Playgroud)
WebHost 只是一个帮助类,它允许我在一行中轻松构建工厂和客户端。
在幕后,它所做的就是:
new WebApplicationFactory<TStartup>() 但还有其他一些事情。
如果我能建立另一个 Web 服务器的另一个实例来测试服务器到服务器的功能,那就 太好了。
有谁知道这是否可能?
Mau*_*eys 18
与接受的答案所述相反,使用两个WebApplicationFactory实例测试服务器到服务器的功能实际上非常容易:
public class OrderAPIFactory : WebApplicationFactory<Order>
{
public OrderAPIFactory() { ... }
protected override void ConfigureWebHost(IWebHostBuilder builder) { ... }
}
public class BasketAPIFactory : WebApplicationFactory<BasketStartup>
{
public BasketAPIFactory() { ... }
protected override void ConfigureWebHost(IWebHostBuilder builder) { ... }
}
Run Code Online (Sandbox Code Playgroud)
然后您可以按如下方式实例化自定义工厂:
[Fact]
public async Task TestName()
{
var orderFactory = new OrderAPIFactory();
var basketFactory = new BasketAPIFactory();
var orderHttpClient = orderFactory.CreateClient();
var basketHttpClient = basketFactory.CreateClient();
// you can hit eg an endpoint on either side that triggers server-to-server communication
var orderResponse = await orderHttpClient.GetAsync("api/orders");
var basketResponse = await basketHttpClient.GetAsync("api/basket");
}
Run Code Online (Sandbox Code Playgroud)
我也不同意关于它必然是糟糕设计的公认答案:它有它的用例。我的公司有一个微服务基础设施,它依赖于跨微服务的数据复制,并使用带有集成事件的异步消息队列来确保数据一致性。毋庸置疑,消息传递功能起着核心作用,需要正确测试。在这种情况下,此处描述的测试设置非常有用。例如,它允许我们彻底测试在这些消息发布时已关闭的服务如何处理消息:
[Fact]
public async Task DataConsistencyEvents_DependentServiceIsDown_SynchronisesDataWhenUp()
{
var orderFactory = new OrderAPIFactory();
var orderHttpClient = orderFactory.CreateClient();
// a new order is created which leads to a data consistency event being published,
// which is to be consumed by the BasketAPI service
var order = new Order { ... };
await orderHttpClient.PostAsync("api/orders", order);
// we only instantiate the BasketAPI service after the creation of the order
// to mimic downtime. If all goes well, it will still receive the
// message that was delivered to its queue and data consistency is preserved
var basketFactory = new BasketAPIFactory();
var basketHttpClient = orderFactory.CreateClient();
// get the basket with all ordered items included from BasketAPI
var basketResponse = await basketHttpClient.GetAsync("api/baskets?include=orders");
// check if the new order is contained in the payload of BasketAPI
AssertContainsNewOrder(basketResponse, order);
}
Run Code Online (Sandbox Code Playgroud)
可以在单个集成测试中托管 WebApplicationFactory 的多个通信实例。
假设我们有名为 的主服务WebApplication,它依赖于WebService使用名为“WebService”的 HttpClient 命名的实用程序服务。
这是集成测试的示例:
[Fact]
public async Task GetWeatherForecast_ShouldReturnSuccessResult()
{
// Create application factories for master and utility services and corresponding HTTP clients
var webApplicationFactory = new CustomWebApplicationFactory();
var webApplicationClient = webApplicationFactory.CreateClient();
var webServiceFactory = new WebApplicationFactory<Startup>();
var webServiceClient = webServiceFactory.CreateClient();
// Mock dependency on utility service by replacing named HTTP client
webApplicationFactory.AddHttpClient(clientName: "WebService", webServiceClient);
// Perform test request
var response = await webApplicationClient.GetAsync("weatherForecast");
// Assert the result
response.EnsureSuccessStatusCode();
var forecast = await response.Content.ReadAsAsync<IEnumerable<WeatherForecast>>();
Assert.Equal(10, forecast.Count());
}
Run Code Online (Sandbox Code Playgroud)
这段代码需要CustomWebApplicationFactory类来实现:
// Extends WebApplicationFactory allowing to replace named HTTP clients
internal sealed class CustomWebApplicationFactory
: WebApplicationFactory<WebApplication.Startup>
{
// Contains replaced named HTTP clients
private ConcurrentDictionary<string, HttpClient> HttpClients { get; } =
new ConcurrentDictionary<string, HttpClient>();
// Add replaced named HTTP client
public void AddHttpClient(string clientName, HttpClient client)
{
if (!HttpClients.TryAdd(clientName, client))
{
throw new InvalidOperationException(
$"HttpClient with name {clientName} is already added");
}
}
// Replaces implementation of standard IHttpClientFactory interface with
// custom one providing replaced HTTP clients from HttpClients dictionary
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
builder.ConfigureServices(services =>
services.AddSingleton<IHttpClientFactory>(
new CustomHttpClientFactory(HttpClients)));
}
}
Run Code Online (Sandbox Code Playgroud)
最后,CustomHttpClientFactory需要类:
// Implements IHttpClientFactory by providing named HTTP clients
// directly from specified dictionary
internal class CustomHttpClientFactory : IHttpClientFactory
{
// Takes dictionary storing named HTTP clients in constructor
public CustomHttpClientFactory(
IReadOnlyDictionary<string, HttpClient> httpClients)
{
HttpClients = httpClients;
}
private IReadOnlyDictionary<string, HttpClient> HttpClients { get; }
// Provides named HTTP client from dictionary
public HttpClient CreateClient(string name) =>
HttpClients.GetValueOrDefault(name)
?? throw new InvalidOperationException(
$"HTTP client is not found for client with name {name}");
}
Run Code Online (Sandbox Code Playgroud)
您可以在这里找到示例的完整代码: https: //github.com/GennadyGS/AspNetCoreIntegrationTesting
这种方法的优点是:
这种方法的主要缺点是,由于测试中使用的所有服务都在单个进程中运行,因此在现实场景中参与服务(例如 EFCore 的不同主要版本)可能会出现依赖冲突。有几种缓解此类问题的方法。其中之一是将模块化方法应用于服务的实现,并根据配置文件在运行时加载模块。这可能允许替换测试中的配置文件,从加载中排除多个模块,并用更简单的模拟替换丢失的服务。您可以在上面示例存储库的“模块化”分支中找到应用这种方法的示例。
| 归档时间: |
|
| 查看次数: |
2664 次 |
| 最近记录: |