Ordered Tests with Rhino Mocks AAA Syntax

Before the AAA syntax was introduced, you would create ordered unit tests by wrapping Expect calls in a using block like so:

var mocks = new MockRepository();
using (mocks.Ordered())
{
    // ...
}

However, AAA syntax does not require you to instantiate a MockRepository, so how can we do ordered tests? This can be accomplished by accessing the implied MockRepository via the GetMockRepository method.

var myMock = MockRepository.GenerateMock<IMyInterface>();
using (myMock.GetMockRepository().Ordered())
{
    // ...
}

Here’s a complete example.

[TestMethod]
public void RunTest()
{
    // Arrange
    var target = new Program();
    var mockModel = MockRepository.GeneratePartialMock<MyModel>();
    target.Model = mockModel;

    using (mockModel.GetMockRepository().Ordered())
    {
        mockModel.Expect(x => x.Populate());
        mockModel.Expect(x => x.Save());
    }

    // Act
    target.Run();

    // Assert
    mockModel.VerifyAllExpectations();
}
// This fails
public void Run()
{
    Model.Save();
    Model.Populate();
}

// This passes
public void Run()
{
    Model.Populate();
    Model.Save();
}
Advertisement

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: