配置MassTransit以使用WebApplicationFactory <Startup>进行测试

时间:2019-08-18 03:59:11

标签: .net-core rabbitmq integration-testing masstransit rawrabbit

我有一个ASP.NET Core Web应用程序,并使用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注册到我的容器中而不在测试中模拟它。不知道InMemoryTestFixtureBusTestFixture还是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;
}

3 个答案:

答案 0 :(得分:1)

在启动期间定义的 MassTransit 配置可以替换为具有自定义 WebApplicationFactory 的新配置,方法是从 MassTransit 命名空间中删除服务,例如

public class CustomWebApplicationFactory : WebApplicationFactory<Startup>  
{   
    protected override void ConfigureWebHost(IWebHostBuilder builder) 
    {
      builder.ConfigureServices(services => 
      {
           var descriptors = services.Where(d => 
                  d.ServiceType.Namespace.Contains("MassTransit",StringComparison.OrdinalIgnoreCase))
                                     .ToList();
         foreach (var d in descriptors) 
         {
           services.Remove(d);
         }     

         services.AddMassTransitInMemoryTestHarness(x =>
         {
           //add your consumers (again)
         });
      });
   }
}

那么你的测试可能看起来像

public class TestClass : IClassFixture<CustomApplicationFactory> 
 {
    private readonly CustomApplicationFactoryfactory;

    public TestClass(CustomApplicationFactoryfactory)
    {
      this.factory = factory;
    }

    [Fact]    
    public async Task TestName()
    {   
      CancellationToken cancellationToken = new CancellationTokenSource(5000).Token;  
      var harness = factory.Services.GetRequiredService<InMemoryTestHarness>();
      await harness.Start();

      var bus = factory.Services.GetRequiredService<IBusControl>();
      try
      {
        await bus.Publish<MessageClass>(...some message...);      
        
        bool consumed = await harness.Consumed.Any<MessageClass>(cancellationToken);
        //do your asserts
      }
      finally
      {
        await harness.Stop();
      }
    }   
  }

重要提示:

  • 如果在启动期间调用了 services.AddMassTransitHostedService();,这将不起作用(因此它应该在测试执行期间以某种方式被排除)。

答案 1 :(得分:0)

最好的选择是使用InMemoryTestHarness,以便可以确保可以对消息合同进行序列化,对使用者进行正确配置,并且可以确保一切正常。尽管有些人可能将其称为集成测试,但实际上只是在进行适当的测试。而且它非常快,因为它全部在内存中。

您可以看到单元测试here,但下面还会显示一个简短的示例。

[TestFixture]
public class When_a_consumer_is_being_tested
{
    InMemoryTestHarness _harness;
    ConsumerTestHarness<Testsumer> _consumer;

    [OneTimeSetUp]
    public async Task A_consumer_is_being_tested()
    {
        _harness = new InMemoryTestHarness();
        _consumer = _harness.Consumer<Testsumer>();

        await _harness.Start();

        await _harness.InputQueueSendEndpoint.Send(new A());
    }

    [OneTimeTearDown]
    public async Task Teardown()
    {
        await _harness.Stop();
    }

    [Test]
    public void Should_have_called_the_consumer_method()
    {
        _consumer.Consumed.Select<A>().Any().ShouldBe(true);
    }


    class Testsumer :
        IConsumer<A>
    {
        public async Task Consume(ConsumeContext<A> context)
        {
            await context.RespondAsync(new B());
        }
    }


    class A
    {
    }


    class B
    {
    }
}

答案 2 :(得分:0)

我最终从WebApplicationFactory中创建了一个方法,

    public void ConfigureTestServiceBus(Action<IServiceCollectionConfigurator> configurator)
    {
        this._configurator = configurator;
    }

让我能够从派生的集成类构造函数中注册测试处理程序;

    public Intg_GetCustomers(WebApplicationTestFactory<Startup> factory)
        : base(factory)
    {
        factory.ConfigureTestServiceBus(c =>
        {
            c.AddConsumer<TestGetProductConsumer>();
        });
    }

当我调用扩展方法以添加MassTransit的InMemory实例时,将使用此配置器

public static IWebHostBuilder ConfigureTestServiceBus(this IWebHostBuilder webHostBuilder, Action<IServiceCollectionConfigurator> configurator)
{
    return webHostBuilder
        .ConfigureTestServices(services =>
        {
            // UseInMemoryServiceBus DI for MassTransit.
            services.AddMassTransit(c =>
            {
                configurator?.Invoke(c);

                // Add bus to the container.
                c.AddBus(provider =>
                {
                    var control = Bus.Factory.CreateUsingInMemory(cfg =>
                    {
                        cfg.ConfigureEndpoints(provider);
                    });

                    control.Start();

                    return control;
                });
            });

            services.AddSingleton<IMessageDataRepository, InMemoryMessageDataRepository>();
        });
}