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

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 )

Google+ photo

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

Connecting to %s