Advance Mocking with Rhino Mocks 3.5

time to read 1 min | 199 words

Here is why I love Rhino Mocks. This is a test that utilize quite a bit of the underlying power of Rhino Mocks. Check this out:

[Test]
public void For_each_batch_from_repository_will_create_and_execute_command()
{
	var stubbedCommand = MockRepository.GenerateMock<ICommand>();
	var mocks = new MockRepository();
	var queueProcessor = mocks.PartialMock<QueueProcessor>(
		stubbedQueueFactory, 
		stubbedOutgoingMessageRepository);

	queueProcessor
		.Stub(x => x.CreateCommand(Arg<SingleDestinationMessageBatch>.Is.Anything))
		.Return(stubbedCommand)
		.Repeat.Any();

	stubbedCommand.Expect(x => x.Execute()).Repeat.Times(3);

	mocks.ReplayAll();

	stubbedOutgoingMessageRepository
		.Stub(x => x.GetBatchOfMessagesToSend())
		.Return(new MessageBatch
		{
			DestinationBatches = new[]
			{
				new SingleDestinationMessageBatch(),
				new SingleDestinationMessageBatch(),
				new SingleDestinationMessageBatch(),
			}
		});

	stubbedOutgoingMessageRepository
		.Stub(x => x.GetBatchOfMessagesToSend())
		.Return(new MessageBatch())
		.Do(delegate { queueProcessor.Stop(); });

	queueProcessor.Run();

	stubbedCommand.VerifyAllExpectations();
}

I use a partial mock to override a single method, use AAA for really nice syntax, the new Do() to allow me to have fine grain control over what is going on and in general mess about with complete control over all the knobs there are.

And just for completion sake, here is the code under test:

public void Run()
{
	while (shouldStop == false)
	{
		checkForMessages.WaitOne(TimeSpan.FromSeconds(1), false);
		MessageBatch messageBatch;
		do // as long as there are messages we don't want to wait
		{
			messageBatch = outgoingMessageRepository.GetBatchOfMessagesToSend();
			foreach (var batch in messageBatch.DestinationBatches)
			{
				ICommand cmd = CreateCommand(batch);
				cmd.Execute();
			}
		} while (messageBatch.IsEmpty == false && shouldStop == false);
	}
}

Sweet!