2011-07-20 58 views
5

下面的代碼編譯,運行,不正是我期待 - 在GreetingPublisher調用bus.Publish()時,引發該事件 - 但起訂量設置不相匹配:如何使用Moq來測試對NServiceBus IBus.Publish()的調用?

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() 

我是否缺少明顯的東西?

回答

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(); 

和它的作品如預期 - 迪倫)

+0

啊......我沒有意識到It.IsAny 不會匹配實現T的類...謝謝! –

+0

我目前正在處理這個問題。 'It.IsAny ()'_does_匹配通用接口到Moq中的具體實現,當_not_ mocking'NServiceBus.IBus'時,甚至可以像通用接口類型的數組那樣行爲(例如在'IBus.Publish '方法),但由於某些原因,在嘲笑'IBus'時失敗。這似乎與特定類型的混淆有關,可能源於NServiceBus將消息作爲通過具體代理的接口進行處理,儘管爲什麼它需要在Publish上執行此操作,但目前無法解決這個問題。 – sennett

+0

@sennett:我建議你用一些示例代碼發佈一個新的問題。這會讓你更容易幫助你。 –