Friday, 5 April 2013

Moq - Checking the Order of Methods Called

Say we have codes like below that call two methods:
public void InsertOrUpdate(ItemDto itemDto)
    . . .
    . . .

We would like to ensure that a method is called after the other. We can use the Callback feature in Moq and a collection type to store predefined values for each method. Then we can check the values stored in the collection and their orders to determine that the methods were called in sequence.
public void SaveChanges_method_is_called_after_Add_method()
    // Arrange
    List<string> invokes = new List<string>();
    string addMethod = "Add";
    string saveChangesMethod = "SaveChanges";
    context.Setup(c => c.Add<Item>(It.IsAny<Item>()))
           .Callback(() => invokes.Add(addMethod));
    context.Setup(c => c.SaveChanges())
           .Callback(() => invokes.Add(saveChangesMethod));
    // Act
    // Assert
    Assert.Equal(invokes[0], addMethod);
    Assert.Equal(invokes[1], saveChangesMethod);

No comments: