Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Moq to test calls to NServiceBus IBus.Publish()?

The following code compiles, runs, does exactly what I'm expecting - the GreetingPublisher calls bus.Publish() when the event is raised - but the Moq setup isn't being matched:

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;
    }
}

and when running the test, I get:

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

Am I missing something obvious?

like image 579
Dylan Beattie Avatar asked Jul 20 '11 12:07

Dylan Beattie


1 Answers

If I see it correctly, your code calls IBus.Publish<HelloMessage> and not IBus.Publish<IMessage>.

(EDIT: I replaced

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

with:

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

and it works as expected - Dylan)

like image 186
Daniel Hilgarth Avatar answered Sep 24 '22 13:09

Daniel Hilgarth