c# - 如何在RhinoMocks中按指定条件从方法返回值?

标签 c# unit-testing rhino-mocks rhino-mocks-3.5

如何使用RhinoMocks模拟以下行为?

测试的方法调用接口(interface)上的 ReceivePayment 方法。

public void TestedMethod(){
    bool result = interface.ReceivePayment();        
}

接口(interface)有CashAccepted事件。 如果此事件已被调用多次(或通过条件),则 ReceivePayment 应返回 true。

如何完成这样的任务?

更新。

现在我执行以下操作:

UpayError error;
        paymentSysProvider.Stub(i => i.ReceivePayment(ticketPrice,
            App.Config.SellingMode.MaxOverpayment, uint.MaxValue, out error))
            .Do( new ReceivePaymentDel(ReceivePayment));

        paymentSysProvider.Stub(x => x.GetPayedSum()).Return(ticketPrice);

        session.StartCashReceiving(ticketPrice);

        paymentSysProvider.Raise(x => x.CashInEvent += null, cashInEventArgs);

public delegate bool ReceivePaymentDel(uint quantityToReceive, uint maxChange, uint maxTimeout, out UpayError error);
public bool ReceivePayment(uint quantityToReceive, uint maxChange, uint maxTimeout, out UpayError error) {
        Thread.Sleep(5000);
        error = null;
        return true;
    }

StartCashReceiving 立即返回,因为内部有任务启动。 但下一行: paymentSysProvider.Raise(...) 正在等待 ReceivePayment stub 的完成!

最佳答案

您可以使用WhenCalled。实际上我不明白你的问题(该事件是由模拟还是由被测单元触发?谁在处理该事件?)

有一些示例代码:

bool fired = false;

// set a boolean when the event is fired.
eventHandler.Stub(x => x.Invoke(args)).WhenCalled(call => fired = true);

// dynamically return whether the eventhad been fired before.
mock
  .Stub(x => x.ReceivePayment())
  .WhenCalled(call => call.ReturnValue = fired)
  // make rhino validation happy, the value is overwritten by WhenCalled
  .Return(false);

当您在测试中触发事件时,您还可以在触发后重新配置模拟:

mock
  .Stub(x => x.ReceivePayment())
  .Return(false);

paymentSysProvider.Raise(x => x.CashInEvent += null, cashInEventArgs);

mock
  .Stub(x => x.ReceivePayment())
  .Return(true)
  .Repeat.Any(); // override previous return value.

关于c# - 如何在RhinoMocks中按指定条件从方法返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20702484/

相关文章:

c# - 将字母表中的所有字母创建为字符串的最有效方法

c# - 在队列上运行多个线程的情况下访问 ConcurrentQueue 的最新元素

c# - 如何在 Windows 10 UWP 中为网格添加触摸操作事件?

.net - FsCheck 和 NUnit 集成

c# - 使用 Rhino Mocks 模拟 IObjectSet<T>

c# - 在回调方法中模拟参数

c# - 模拟私有(private)领域

c# - 在MongoDB中存储DateTime对性能的影响

unit-testing - TFS 2010 构建自动化 - 启用代码覆盖

ruby-on-rails - 使用子存在验证创建父子 Factory Girl