给出一种模拟方法...
public bool TryReceive(out T message, TimeSpan millisecondsToWait)
- 我希望在前两次调用中设置不同的消息,然后返回
真的。
- 后续调用将返回 false。
我尝试了一些变体,无论哪种情况,lambda 表达式执行一次,再也不会了。 N替代品似乎是缓存第一个返回值,并反复使用相同的值。
我已经尝试过这个...
TCR @out;
var container = new AutoSubstitute();
var mb = container.Resolve<IMessageBuffer<TCR>>();
mb.TryReceive(out @out, Arg.Any<TimeSpan>()).Returns(
_ => { _[0] = buy; return true; },
_ => { _[0] = sell; return true; },
_ => { _[0] = null; return false; });
我已经尝试过这个:
bool? bs = true;
TCR @out;
var container = new AutoSubstitute();
var mb = container.Resolve<IMessageBuffer<TCR>>();
mb.TryReceive(out @out, Arg.Any<TimeSpan>()).Returns(
_ =>
{
if (bs == true)
{
_[0] = buy;
bs = false;
return true;
}
if (bs == false)
{
_[0] = sell;
bs = null;
return true;
}
_[0] = null;
return false;
});
我能想到的唯一选择是提供缓冲区的完整替代实现以用于测试目的。我的感觉是鉴于此文档 http://nsubstitute.github.io/help/setting-out-and-ref-arguments/,应该是可以的。
edit
我无法使用 NSubstitute 来实现这一点,但是如果我提供一个模拟实现IMessageBuffer<TCR>
using
// mock buffer will return the necessary values by maintaining
// the relevant state internally.
container.Provide<IMessageBuffer<TCR>>(new MockBuffer());
它工作正常,所以这不是一个生命周期问题。不知何故, NSubstitute 似乎只在第一次调用模拟出的方法,并重用该值(或以这样的方式操作)seems重用该值) - 很奇怪。