Can I test method call order with AAA syntax in Rhino-Mocks 3.6?

后端 未结 5 1544
南笙
南笙 2020-12-19 01:19

Is it possible to test for the following example if the Method1 called 1st, then Method2 called after and then Method3 by using the AAA syntax, in Rhino-mocks 3.6 ?

5条回答
  •  青春惊慌失措
    2020-12-19 01:48

    Here's how to do it by building assertions into each method invocation.

    // Arrange - Build the necessary assertions into the stubbed method invocations.
    var mock = MockRepository.GenerateMock();
    mock.Stub(m => m.Method1()).WhenCalled(inv => mock.AssertWasNotCalled(m => m.Method2()));
    mock.Stub(m => m.Method2()).WhenCalled(inv => mock.AssertWasNotCalled(m => m.Method3()));
    
    // Act
    myObject.Service = mock;
    
    // Assert - Ensure each expected method was called.
    mock.AssertWasCalled(m => m.Method1());
    mock.AssertWasCalled(m => m.Method2());
    mock.AssertWasCalled(m => m.Method3());
    

    Since this is mixes up normal arrange-act-assert pattern by running assertions in mid-act, I like to include very specific error messages for these instances to identify test failures more easily.

    mock.Stub(m => m.Method1()).WhenCalled(inv =>
        mock.AssertWasNotCalled(m => m.Method2(), opt =>
            opt.Message("Method2 cannot be called before Method1.")));
    

    You could also achieve a similar result by saving the result of each invocation in a variable during the act step, and then checking the variable states during the assert step. This better preserves the division of the arrange-act-assert pattern, but it is more plumbing code to write and maintain.

    // Arrange - Build the necessary state variables into the stubbed method invocations.
    bool wasMethod1Called;
    bool wasMethod2Called;
    bool wasMethod2CalledBeforeMethod1;
    bool wasMethod3CalledBeforeMethod2;
    
    var mock = MockRepository.GenerateMock();
    mock.Stub(m => m.Method1()).WhenCalled(inv =>
    {
        wasMethod1Called = true;
    });
    mock.Stub(m => m.Method2()).WhenCalled(inv =>
    {
        wasMethod2Called = true;
        wasMethod2CalledBeforeMethod1 = !wasMethod1Called;
    });
    mock.Stub(m => m.Method3()).WhenCalled(inv =>
    {
        wasMethod3CalledBeforeMethod2 = !wasMethod2Called;
    });
    
    // Act
    myObject.Service = mock;
    
    // Assert - Ensure each expected method was called, and that they were called in the right order.
    mock.AssertWasCalled(m => m.Method1());
    mock.AssertWasCalled(m => m.Method2());
    mock.AssertWasCalled(m => m.Method3());
    Assert.That(wasMethod2CalledBeforeMethod1, Is.False, "Method2 cannot be called before Method1.");
    Assert.That(wasMethod3CalledBeforeMethod2, Is.False, "Method3 cannot be called before Method2.");
    

提交回复
热议问题