我有一个ASP.NET Core网站应用程序和测试设置,使用
WebApplicationFactory
测试我的控制器操作。之前我使用过RawRabbit,很容易模拟IBusClient
并将其添加到DI容器中作为单例。在WebApplicationFactory<TStartup>.CreateWebHostBuilder()
中,我调用这个扩展方法来添加已模拟的IBusClient
实例,像这样;/// <summary>
/// Configures the service bus.
/// </summary>
/// <param name="webHostBuilder">The web host builder.</param>
/// <returns>A web host builder.</returns>
public static IWebHostBuilder ConfigureTestServiceBus(this IWebHostBuilder webHostBuilder)
{
webHostBuilder.ConfigureTestServices(services =>
{
services.AddSingleton<IBusClient, MY_MOCK_INSTANCE>
});
return webHostBuilder;
}
目前 RawRabbit 存在一些缺陷,这使我决定转向 MassTransit。但是,我想知道是否已经有更好的方法将 IBus
注册到容器中,而不必在测试中模拟它。不确定 InMemoryTestFixture
、BusTestFixture
或者 BusTestHarness
是否能解决我的问题。也不确定它们如何一起使用以及它们的功能。
顺便说一下,在我的 ASP.NET Core 应用程序中,我有一个可重复使用的扩展方法设置,如下所示的代码,可以在启动时连接到 RabbitMQ。
/// <summary>
/// Adds the service bus.
/// </summary>
/// <param name="services">The services.</param>
/// <param name="configurator">The configurator.</param>
/// <returns>A service collection.</returns>
public static IServiceCollection AddServiceBus(this IServiceCollection services, Action<IServiceCollectionConfigurator> configurator)
{
var rabbitMqConfig = new ConfigurationBuilder()
.AddJsonFile("/app/configs/service-bus.json", optional: false, reloadOnChange: true)
.Build();
// Setup DI for MassTransit.
services.AddMassTransit(x =>
{
configurator(x);
// Get the json configuration and use it to setup connection to RabbitMQ.
var rabbitMQConfig = rabbitMqConfig.GetSection(ServiceBusOptionsKey).Get<RabbitMQOptions>();
// Add bus to the container.
x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
{
cfg.Host(
new Uri(rabbitMQConfig.Host),
hostConfig =>
{
hostConfig.Username(rabbitMQConfig.Username);
hostConfig.Password(rabbitMQConfig.Password);
hostConfig.Heartbeat(rabbitMQConfig.Heartbeat);
});
cfg.ConfigureEndpoints(provider);
// Add Serilog logging.
cfg.UseSerilog();
}));
});
// Add the hosted service that starts and stops the BusControl.
services.AddSingleton<IMessageDataRepository, EncryptedMessageDataRepository>();
services.AddSingleton<IEndpointNameFormatter, EndpointNameFormatter>();
services.AddSingleton<IBus>(provider => provider.GetRequiredService<IBusControl>());
services.AddSingleton<IHostedService, BusHostedService>();
return services;
}
services.AddSingleton<IBus>(provider => provider.GetRequiredService<IBusControl>());
- Chris Patterson