简体   繁体   English

使用 XUnit 对大众运输消费者进行单元测试

[英]Unit Testing MassTransit Consumer With XUnit

My team is just getting started with using MassTransit and we are trying to figure out how unit testing IConsumer implementations work.我的团队刚刚开始使用 MassTransit,我们正试图弄清楚单元测试 IConsumer 实现是如何工作的。 The MassTransit documentation is incomplete and all of the examples I have found so far use NUnit. MassTransit 文档不完整,到目前为止我发现的所有示例都使用 NUnit。 We are trying to use XUnit with Moq to do our unit testing.我们正在尝试使用 XUnit 和 Moq 来进行单元测试。

I know that we need to set up one instance of the MassTransit test harness, which in NUnit is done with a OneTimeSetup and to replicate that we should use IClassFixture in XUnit.我知道我们需要设置 MassTransit 测试工具的一个实例,在 NUnit 中使用 OneTimeSetup 完成,并复制我们应该在 XUnit 中使用 IClassFixture。 I'm struggling with getting that to work with the test harness, though.不过,我正在努力让它与测试工具一起工作。

I have seen Chris Patterson's ConsumerTest_Specs.cs example on the MassTransit GitHub, but I'm having a hard time translating it to work in XUnit and Moq.我在 MassTransit GitHub 上看到了 Chris Patterson 的 ConsumerTest_Specs.cs 示例,但我很难将其翻译成在 XUnit 和 Moq 中工作。 https://github.com/MassTransit/MassTransit/blob/master/src/MassTransit.Tests/Testing/ConsumerTest_Specs.cs https://github.com/MassTransit/MassTransit/blob/master/src/MassTransit.Tests/Testing/ConsumerTest_Specs.cs

I'm trying to test a very simple consumer to start with.我正在尝试测试一个非常简单的消费者。 All it does is receive the message and then make a call to a repository.它所做的只是接收消息,然后调用存储库。 I want to write an XUnit test that mocks the repository and verifies that the repository method was called.我想编写一个 XUnit 测试来模拟存储库并验证是否调用了存储库方法。

Does anyone have any examples of how to do something like this?有没有人有任何关于如何做这样的事情的例子?

public class NewVMRequestRejectedConsumer : IConsumer<INewVMRequestRejected>
{
    private readonly INewVMRequestRepository _newVMRequestRepository;

    public NewVMRequestRejectedConsumer(INewVMRequestRepository newVMRequestRepository)
    {
        _newVMRequestRepository = newVMRequestRepository;
    }

    public Task Consume(ConsumeContext<INewVMRequestRejected> context)
    {
        _newVMRequestRepository.AddReasonForRejection(context.Message.RequestId, context.Message.Reason);
        return Task.CompletedTask;
    }
}

Since ConsumeContext<out T> and INewVMRequestRepository are interfaces there is no problem mocking them using moq , eg由于ConsumeContext<out T>INewVMRequestRepository是接口,因此使用moq INewVMRequestRepository它们没有问题,例如

//Arrange
var repository = new Mock<INewVMRequestRepository>();
var sut = new NewVMRequestRejectedConsumer(repository.Object);

//Act
sut.Consume(Mock.Of<ConsumeContext<INewVMRequestRejected>>(m =>
    m.Message.RequestId == "id" && m.Message.Reason == "reason"));

//Assert
repository.Verify(m => m.AddReasonForRejection("id", "reason"), Times.Once);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM