Moq - 验证对方法的最后一次调用

时间:2013-01-25 10:51:43

标签: c# unit-testing moq

public interface IMouseTraits
{
    void ForceCursor(Cursor cursor);
    void SetCursor(Cursor cursor);
}

1)如何验证对SetCursor的最后一次调用是Cursors.Arrow(多次调用SetCursor和ForceCursor,允许使用不同的参数)。

2)如何验证SetCursorForceCursor的最后一次调用是SetCursor(允许多次调用SetCursor和ForceCursor,允许使用不同的参数)。

[Test]
public void AfterOperationCursorIsArrow()
{
    var mock = new Mock<IMouseTraits>();

    varw = new WindowOperation(mock.Object);
    w.Execute();

    mock.Verify(traits => traits.SetCursor(Cursors.Arrow));  // ?
}

1 个答案:

答案 0 :(得分:5)

您可以使用Callbacks捕获来电:

[Test]
public void AfterOperationCursorIsArrow()
{
    string lastMethod = null;
    Cursor lastCursor = null;

    var mock = new Mock<IMouseTraits>();

    mock.Setup(m => m.ForceCursor(It.IsAny<Cursor>()))
        .Callback((Cursor c) => lastMethod = "ForceCursor");

    mock.Setup(m => m.SetCursor(It.IsAny<Cursor>()))
        .Callback((Cursor c) => { 
            lastMethod = "SetCursor";
            lastCursor = c; 
        });

    var w = new WindowOperation(mock.Object);
    w.Execute();

     Assert.That(lastMethod, Is.EqualTo("SetCursor"));
     Assert.That(lastCursor, Is.EqualTo(Cursors.Arrow));
}