【问题标题】:Reset a mock in RhinoMocks在 RhinoMocks 中重置模拟
【发布时间】:2011-04-20 08:25:21
【问题描述】:

我正在用 RhinoMocks 编写 NUnit 测试。其中一项测试如下所示:

mock = MockRepository<IFoo>.CreateMock();

// Arrange
// During the Arrange part, mock.MyMethod() gets called several times.

// Act
// During the Act part, mock.MyMethod() should be called exactly once.

// Assert
mock.AssertWasCalled(x => x.MyMethod()).Repeat.Once();

这自然会失败,因为 MyMethod() 已被多次调用。

有没有办法可以在 Act 部分之前重置对 MyMethod() 的调用计数,以便仅捕获重置后的调用?

【问题讨论】:

  • 这感觉有点奇怪。为什么mock.MyMethod() 在排列部分被多次调用?只是为了让我们更多地了解您的代码。

标签: c# mocking rhino-mocks


【解决方案1】:

我认为@alexl 引用的 SO 问题应该可以帮助您。但是我很好奇在测试的 Act 阶段之外调用模拟的情况是什么。这可能表明您的对象之间的耦合过于紧密。

作为一种可能的解决方法,如果在 Arrange 期间没有保留状态信息,您始终可以创建另一个仅在 Arrange 阶段使用的 IFoo 模拟。

【讨论】:

    【解决方案2】:
    // Arrange
    // During the Arrange part, mock.MyMethod() gets called several times.
    
    var mockRep = new MockRepository();
    var mock = mockRep.dynamicMock<IFoo>();
    Expect.Call(mock.MyMethod()).Return("desired result").Repeat.Time("count");
    
    mock.Replay()
    
    // Act
    //test go here 
    
    // Assert
    mock.AssertWasCalled(x => x.MyMethod()).Repeat.Once();
    

    【讨论】:

      【解决方案3】:

      也许这篇文章可以帮助你:How to clear previous expectations on an object?

      Mock.BackToRecord() 会这样做

      【讨论】:

      • 我认为这不会清除调用方法的次数,只会重置存根返回值。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      相关资源
      最近更新 更多