【问题标题】:Clear call history of a mock清除模拟的通话记录
【发布时间】:2013-07-02 12:14:54
【问题描述】:

问题:是否可以清除模拟(或存根)的调用历史?
(对于通话记录,我并不是指预期/记录的行为。)

详情:
我目前想根据 AAA 语法使用 NUnit 和 Rhino 模拟编写以下代码并进行测试。

public abstract class MockA
{
    private bool _firstTime = true;

    public void DoSomething()
    {
        if (_firstTime)
        {
            OnFirstDoSomething();
            _firstTime = false;
        }
    }

    public abstract void OnFirstDoSomething();
}

[TestFixture]
public class MockATest
{
    [Test]
    public void DoSomethingShouldSkipInitializationForSequentialCalls()
    {
        // Arrange
        var mockA = MockRepository.GeneratePartialMock<MockA>();
        mockA.Expect(x => x.OnFirstDoSomething()).Repeat.Any();
        mockA.DoSomething();  // -> OnFirstDoSomething() is called
        // here I want clear the call history of mockA 

        //Act
        mockA.DoSomething(); // -> OnFirstDoSomething should NOT be called
        mockA.DoSomething(); // -> OnFirstDoSomething should NOT be called

        //assert
        mockA.AssertWasNotCalled(x => x.OnFirstDoSomething());
    }
}

为了便于阅读,我总是尝试将 Assert 部分中的调用重点放在 Act 部分中发生的更改上。
但是,此测试中的安排部分包含影响 mockA 调用历史的(必需)操作。
结果断言失败。

我知道我可以使用下面的构造来捕捉通话历史记录中的“变化”,但它会降低该测试的预期行为的可读性。

{
    ...
    mockA.AssertWasCalled(x => x.OnFirstDoSomething(), opt => opt.Repeat.Once());
    //Act
    mockA.DoSomething();
    //Assert
    mockA.AssertWasCalled(x => x.OnFirstDoSomething(), opt => opt.Repeat.Once());
}

我的问题:是否可以清除模拟的通话记录(未记录的期望)?

【问题讨论】:

    标签: rhino-mocks arrange-act-assert


    【解决方案1】:

    您无需清除通话记录。在 Arrange 部分使用 Stub 方法而不是 Expect:

    [Test]
    public void DoSomethingShouldSkipInitializationForSequentialCalls()
    {
        // Arrange
        var mockA = MockRepository.GeneratePartialMock<MockA>();
    
        // this is what you have to change
        mockA.Stub(x => x.OnFirstDoSomething()).Repeat.Any();
        mockA.DoSomething();  // -> OnFirstDoSomething() is called
        // here I want clear the call history of mockA 
    
        //Act
        mockA.DoSomething();
        mockA.DoSomething();
    
        //assert
        mockA.AssertWasNotCalled(x => x.OnFirstDoSomething());
    }
    

    【讨论】:

    • 不幸的是,这行不通。我在测试中添加了“MockA”代码和一些注释以清除预期的行为。
    • 经过几年的 TDD 之后,我决定尝试另一个模拟框架 NSubstitute。我注意到的一件事是,我想要使用 Rhinomock 清除模拟调用历史记录。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多