【问题标题】:How to set the Expect call to check that a method is not called in Rhino Mocks如何设置 Expect 调用以检查 Rhino Mocks 中未调用方法
【发布时间】:2011-10-15 21:04:08
【问题描述】:

使用 Rhino Mocks,如何确保在设置 mock 对象的 Expectations 时不调用方法。

在我的示例中,我正在测试 Commit 方法,我需要确保在执行提交时不调用 Rollback 方法。 (这是因为我在提交方法中有逻辑,如果提交失败会自动回滚)

下面是代码的样子..

[Test]
public void TestCommit_DoesNotRollback() 
{
    //Arrange
    var mockStore = MockRepository.GenerateMock<IStore>();
    mockStore.Expect(x => x.Commit());
    //here i want to set an expectation that x.Rollback() should not be called.

    //Act
    subject.Commit();

    //Assert
    mockStore.VerifyAllExpectation();
}

当然,我可以在 Assert 阶段这样做:

mockStore.AssertWasNotCalled(x => x.Rollback());

但我想首先将其设置为期望。

【问题讨论】:

  • 好奇为什么要使用 Expectation,而不仅仅是 AssertWasNotCalled?
  • @Cousken AssertWasNotCalled() 似乎不适用于 BackToRecord() 和 Replay(),也许这就是原因??

标签: c# unit-testing rhino-mocks


【解决方案1】:

另一种选择是:

mockStore.Expect(x => x.Rollback()).Repeat.Never();

【讨论】:

    【解决方案2】:

    这就是你要找的东西吗?

    ITest test = MockRepository.GenerateMock<ITest>();
    test.Expect(x => x.TestMethod()).AssertWasNotCalled(mi => {});
    

    【讨论】:

      【解决方案3】:

      这是另一种选择:

              mockStore.Stub(x => x.DoThis()).Repeat.Times(0);
      
              //EXECUTION HERE 
      
              x.VerifyAllExpectations();
      

      【讨论】:

        【解决方案4】:

        对于这种情况,我创建了一个扩展方法来更好地展示我的意图

        public static IMethodOptions<RhinoMocksExtensions.VoidType> ExpectNever<T>(this T mock, Action<T> action) where T : class
        {
            return mock.Expect(action).IgnoreArguments().Repeat.Never();
        }
        

        注意 IgnoreArguments() 调用。我假设您不希望该方法被调用...无论参数值是什么。

        【讨论】:

          猜你喜欢
          • 2010-11-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-30
          • 2010-10-03
          • 1970-01-01
          • 2011-03-14
          • 1970-01-01
          相关资源
          最近更新 更多