Dashboard > NMock > Two minute tutorial
Two minute tutorial Log In View a printable version of the current page.

Added by Chris Stevenson , last edited by Chris Stevenson on Mar 30, 2004  (view change)
Labels: 
(None)

This guide assumes you are familiar with unit-testing and NUnit.

For a simple example we are going to test a publish/subscribe message system. A Publisher sends objects to zero or more Subscribers. We want to test the Publisher, which involves testing its interactions with its Subscribers.

The Subscriber interface looks like this:

public interface ISubscriber 
{
	void Receive(Object message);
}

We will test that a Publisher sends a message to a single registered ISubscriber. To test interactions between the Publisher and the ISubscriber we will use a mock ISubscriber.

We first set up the context in which our test will execute. We create a Publisher to test. We create a mock ISubscriber that should receive the message. We then register the ISubscriber with the Publisher. Finally we create a message object to publish.

Mock mockSubscriber = new DynamicMock(typeof(ISubscriber));
Publisher publisher = new Publisher();
publisher.Add((ISubscriber) mockSubscriber.MockInstance);

object message = new Object();

The mockSubscriber we have created implements the ISubscriber interface. It allows us to set up assertions that will be tested when the object under test uses its ISubscriber instance.

Next we define expectations on the mock ISubscriber that specify the methods that we expect to be called upon it during the test run. We expect the Receive method to be called with a single argument, the message that will be sent. We don't need to specify what will be returned from the receive method because it has a void return type.

mockSubscriber.Expect("Receive",message);

We then execute the code that we want to test.

publisher.Publish(message);

Finally we verify that the mock Subscriber was called as expected. If we do not verify, our test will detect incorrect calls to the mock Subscriber but not the complete lack of calls.

mockSubscriber.Verify();

Here is the complete test.

using System;

using NMock;
using NUnit.Framework;

namespace sample.subscriber
{
	[TestFixture]
	public class PublisherTest
	{
		[Test]
		public void OneSubscriberReceivesAMessage()
		{
			// set up
			Mock mockSubscriber = new DynamicMock(typeof(ISubscriber));
			Publisher publisher = new Publisher();
			publisher.Add((ISubscriber) mockSubscriber.MockInstance);

			object message = new Object();

			// expectations
			mockSubscriber.Expect("Receive",message);

			// execute
			publisher.Publish(message);

			// verify
			mockSubscriber.Verify();
		}
	}
}
Powered by a free Atlassian Confluence Open Source Project / Non-profit License granted to ThoughtWorks, Inc.. Evaluate Confluence today.
Powered by Atlassian Confluence 2.7.1, the Enterprise Wiki. Bug/feature request - Atlassian news - Contact administrators