.NET - 使用消息代理测试系统

问题描述 投票:0回答:1

我有一个关于测试我的应用程序的问题,我在其中使用消息代理(公共交通库、Azure 服务总线实现)在服务之间进行通信。假设我有 ServiceA 和 ServiceB。

就集成测试而言,我想很明显我只是启动 ServiceB 和 Message Broker 并进行测试。但是,我更多地想是否有与消息代理进行合同测试之类的事情?我尝试搜索和谷歌搜索,但找不到任何东西。

提前非常感谢。

编辑: ServiceA - 此方法通过公共交通主题消息发送

public async Task Send()
{
  await _publishEndpoint.Publish(new TestMessage(), cancellationToken);
}

ServiceB - 这是 TestMessage 的使用者

  public class TestConsumer : IConsumer<TestMessage>
  {
      public async Task Consume(ConsumeContext<TestMessage> context)
      {
          // Do some work
      }
  }
c# .net testing azureservicebus messagebroker
1个回答
0
投票

以下代码适用于 ServiceA 和 ServiceB 以及集成测试,以使用 Azure 服务总线和 MassTransit 来测试它们之间的消息流:


    {
        var busControl = Bus.Factory.CreateUsingAzureServiceBus(cfg =>
        {
            cfg.Host("your-connection-string");
        });

        await busControl.StartAsync();

        var serviceA = new ServiceA(busControl);
        await serviceA.Send();

        await busControl.StopAsync();
    }
}

public class ServiceA
{
    private readonly IBusControl _busControl;

    public ServiceA(IBusControl busControl)
    {
        _busControl = busControl;
    }

    public async Task Send()
    {
        await _busControl.Publish(new TestMessage { Content = "Hello from ServiceA!" });
        Console.WriteLine("Message sent from ServiceA");
    }
}

public class TestMessage
{
    public string Content { get; set; }
}



测试用例:


[Test]
    public async Task TestMessageFlow()
    {
        // Arrange
        var busControl = Bus.Factory.CreateUsingAzureServiceBus(cfg =>
        {
            cfg.Host("your-connection-string");
        });

        await busControl.StartAsync();

        var serviceA = new ServiceA(busControl);
        var serviceB = new ServiceB(busControl);

        // Act
        await serviceB.StartListening();
        await serviceA.Send();

        // Assert
        // You can add assertions here to verify that ServiceB has received and processed the message
        // For example, check logs, database state, etc.

        await busControl.StopAsync();
    }
}

public class ServiceA
{
    private readonly IBusControl _busControl;

    public ServiceA(IBusControl busControl)
    {
        _busControl = busControl;
    }

    public async Task Send()
    {
        await _busControl.Publish(new TestMessage { Content = "Hello from ServiceA!" });
    }
}



enter image description here

enter image description here

  • 另一种方法是使用 MassTransit 的测试工具进行单元和集成测试
© www.soinside.com 2019 - 2024. All rights reserved.