【问题标题】:Mock IRequestClient<> during Integration Testing using MassTransit在使用 MassTransit 进行集成测试期间模拟 IRequestClient<>
【发布时间】:2022-01-20 04:15:02
【问题描述】:

我正在尝试针对 MediatR 命令进行集成测试,该命令的处理程序依赖于注入到其构造函数中的 IRequestClient。

    public class SayHelloCommand : IRequest<string>
    {
    }

    public class SayHelloCommandHandler : IRequestHandler<SayHelloCommand, string>
    {
        private readonly IRequestClient<IGetProfileMessageResult> _profileClient;

        public SayHelloCommandHandler(IRequestClient<IGetProfileMessageResult> profileClient)
        {
            _profileClient = profileClient;
        }
        public async Task<string> Handle(SayHelloCommand request, CancellationToken cancellationToken)
        {
            var profile = (await _profileClient.GetResponse<IGetProfileMessageResult>(new {ProfileId = 1})).Message;

            return $"Hello {profile.FirstName}";
        }
    }

我已将我的测试套件设置为使用 InMemoryMassTransit,但每当我运行测试时,它会在使用 IRequestClient 到达调用时超时。我也尝试过最小化 IRequestClient 以返回这样的默认响应 -


        [Test]
        public async Task ShouldSayHello()
        {
          
          
            var mockRequestClient = new Mock<IRequestClient<IGetProfileMessageResult>>();
            mockRequestClient.Setup(x => x.GetResponse<IGetProfileMessageResult>(It.IsAny<Object>(), default, default)
            .Result.Message).Returns(new GetProfileMessageResult
            {
                FirstName = "John"
            });

            serviceCollection.Add(new ServiceDescriptor(typeof(IRequestClient<IGetProfileMessageResult>), mockRequestClient.Object));

            var result = await SendAsync(command);

            result.Status.Should().BeFalse();
            result.Message.Should().Contain("John");
        }
            

但这仍然超时。

有没有办法可以设置 InMemoryMassTransit 在调用 requestclient 时返回默认响应?

【问题讨论】:

    标签: .net-core nunit moq masstransit


    【解决方案1】:

    您可以使用内存中的测试工具来设置一个简单的消费者来响应请求,而不是尝试模拟 IRequestClient。尽管您应该可以根据需要模拟它,但我只是不知道正确配置模拟框架的语法。

    有许多使用可用测试工具的示例,以及所有 MassTransit 单元测试。

    【讨论】:

    • 所以你的意思是我应该在同一个服务中编写一个消费者来响应 IRequestClient 客户端调用并将其注册到像 x.Add.ConsumerTestHarness() 这样的设置中?你能指点我你提到的样品吗?顺便说一句,我使用的是起订量
    猜你喜欢
    • 2015-06-15
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 2019-11-24
    • 1970-01-01
    • 2019-05-21
    相关资源
    最近更新 更多