How to test method call order with Moq

I recently created Moq.Sequences which provides the ability to check ordering in Moq. You may want to read my post that describes the following:

  • Supports method invocations, property
    setters and getters.
  • Allows you to specify the number of
    times a specific call should be
    expected.
  • Provides loops which allow you to
    group calls into a recurring group.
  • Allows you to specify the the number
    of times a loop should be expected.
  • Calls that are expected to be called
    in sequence can be inter-mixed with
    calls that are expected in any order.
  • Multi-threaded support.

Typical usage looks like:

[Test]
public void Should_show_each_post_with_most_recent_first_using_sequences()
{
    var olderPost = new Post { DateTime = new DateTime(2010, 1, 1) };
    var newerPost = new Post { DateTime = new DateTime(2010, 1, 2) };
    var posts = new List<Post> { newerPost, olderPost };

    var mockView = new Mock<BlogView>();

    using (Sequence.Create())
    {
        mockView.Setup(v => v.ShowPost(newerPost)).InSequence();
        mockView.Setup(v => v.ShowPost(olderPost)).InSequence();

        new BlogPresenter(mockView.Object).Show(posts);
    }
}

Leave a Comment