下面的代码编译,运行,完全符合我的预期 - 当事件被引发时,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()
我错过了一些明显的东西吗?
答案 0 :(得分:6)
如果我看到的正确,您的代码会调用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();
它按预期工作 - 迪伦)