单元测试 – 如何使用Moq测试对NServiceBus IBus.Publish()的调用?

下面的代码编译,运行,完全符合我的预期 – 当事件被引发时,GreetingPublisher调用bus.Publish() – 但是Moq设置没有匹配:

using Moq;
using NServiceBus;
using NUnit.Framework;

namespace MyProject.Greetifier.Tests {
    [TestFixture]
    public class GreetingPublisher_Bus_Integration_Tests {
        [Test]
        public void Greeting_Is_Published_To_Bus() {
            var mockGreeter = new Mock<IGreeter>();
            var mockBus = new Mock<IBus>();
            mockBus.Setup(bus => bus.Publish<IMessage>(It.IsAny<IMessage>()))
                   .Verifiable();
            var Greetifier = new GreetingPublisher(mockGreeter.Object,
                                                   mockBus.Object);
            mockGreeter.Raise(m => m.Greet += null, "world");
            mockBus.Verify();
        }
    }

    public class HelloMessage : IMessage {
        public string Name { get; set; }
        public HelloMessage(string name) { this.Name = name; }

    }

    public class GreetingPublisher {
        private readonly IGreeter greeter;
        private readonly IBus bus;

        public GreetingPublisher(IGreeter greeter, IBus bus) {
            this.greeter = greeter;
            greeter.Greet += handleGreetEvent;
            this.bus = bus;
        }

        void handleGreetEvent(string name) {
            bus.Publish(new HelloMessage(name));
        }
    }

    public delegate void GreetingEvent(string name);

    public interface IGreeter {
        event GreetingEvent Greet;
    }
}

在运行测试时,我得到:

Test 'MyProject.Greetifier.Tests.GreetingPublisher_Bus_Integration_Tests.Greeting_Is_Published_To_Bus' failed:
Moq.MockVerificationException : The following setups were not matched:
IBus bus => bus.Publish<IMessage>(new[] { It.IsAny<IMessage>() })
at Moq.Mock.Verify()
D:\Projects\MyProject\src\MyProject.Greetifier.Tests\Program.cs(15,0): MyProject.Greetifier.Tests.GreetingPublisher_Bus_Integration_Tests.Greeting_Is_Published_To_Bus()

我错过了一些明显的东西吗

最佳答案
如果我看到它正确,您的代码将调用IBus.Publish< HelloMessage>而不是IBus.Publish< IMessage>.

(编辑:我换了

mockBus.Setup(bus => bus.Publish<IMessage>(It.IsAny<IMessage>()))
               .Verifiable();

有:

mockBus.Setup(bus => bus.Publish<HelloMessage>(It.IsAny<HelloMessage>()))
               .Verifiable();

它按预期工作 – 迪伦)

转载注明原文:单元测试 – 如何使用Moq测试对NServiceBus IBus.Publish()的调用? - 代码日志