【问题标题】:RhinoMocks return value when a method has not been calledRhinoMocks 在方法未被调用时返回值
【发布时间】:2012-12-31 07:49:00
【问题描述】:

我想做以下...

在调用某个方法之前,某个属性必须始终返回值 x 调用方法后,某个属性必须始终返回值 y

我熟悉 RhinoMocks 中的 WhenCalled 方法,它允许我在方法被调用后设置返回值,但我想不出在调用之前设置返回值的方法。到目前为止,我有以下代码...

counter.Expect(n => n.IncreaseCounter())
   .WhenCalled(i => counter.Expect(n => n.GetCounter)
   .Return(Y).Repeat.Any());

这可能吗?

【问题讨论】:

    标签: c# rhino-mocks


    【解决方案1】:

    有两种解决方案可以解决问题:

    1. 使用WhenCalled():

      var counter = MockRepository.GenerateStub<ICounter>();
      
      int cnt = 1;
      
      counter
          .Stub(c => c.GetCounter)
          .Return(0)
          .WhenCalled(invocation => { invocation.ReturnValue = cnt; });
      
      counter
          .Stub(c => c.IncreaseCounter())
          .WhenCalled(invocation => { ++cnt; });
      
    2. 使用Do()处理程序

      var counter = MockRepository.GenerateStub<ICounter>();
      
      int cnt = 1;
      
      counter
          .Stub(c => c.GetCounter)
          .Do((Func<int>)(() => cnt));
      
      counter
          .Stub(c => c.IncreaseCounter())
          .Do((Action)(() => ++cnt));
      

    这两种情况的想法是相同的:最初GetCounter 返回1。每个IncreaseConter() 调用都会增加GetCounter 返回的值。

    PS
    如果您不打算对counter 进行断言,那么使用Stub() 而不是Expect() 设置它可能更合适。参见例如this question了解详情。

    【讨论】:

    • 谢谢亚历克斯,这对我有帮助,这正是我想要的……稍作修改
    【解决方案2】:

    只需在模拟方法的回调中为属性设置新的返回值:

    Mock<IFoo> fooMock = new Mock<IFoo>();
    fooMock.Setup(foo => foo.Property).Returns(1);
    fooMock.Setup(foo => foo.Method())
           .Callback(() => fooMock.Setup(x => x.Property).Returns(42));
    

    模拟的属性将返回1,直到模拟的方法被调用。然后它的返回值将设置为42。所有对模拟属性的进一步调用都将返回42

    【讨论】:

    • 糟糕,我的错 :) 很快就会修复
    【解决方案3】:

    基于亚历山大的解决方案...以下是我正在寻找的...

    var counter = MockRepository.GenerateStub<ICounter>();
    
    int x = 1;
    int y = 2;
    int cnt = x;
    
    counter
        .Stub(c => c.GetCounter)
        .Return(0)
        .WhenCalled(invocation =>
        {
            invocation.ReturnValue = cnt;
            cnt = y;
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多