NSubstitute clearing When()。Do()

时间:2013-09-17 06:53:05

标签: c# .net unit-testing nsubstitute

NSubstitute是否可以清除或删除以前的.When()。Do()配置?

substitute.When(s => s.Method(1)).Do(c => { /* do something */ });
// code

substitute.When(s => s.Method(1)).Clear(); // <-- is this possible?
substitute.When(s => s.Method(1)).Do(c => { /* do something different */ });
// other code

1 个答案:

答案 0 :(得分:6)

查看CallActions的{​​{3}},似乎没有办法删除或替换回调。

使用示例证明缺少替换功能

int state = 0;
var substitute = Substitute.For<IFoo>();

substitute.When(s => s.Bar()).Do(c => state++);
substitute.Bar();
Assert.That(state, Is.EqualTo(1));

substitute.When(s => s.Bar()).Do(c => state--);
substitute.Bar();

// FAIL: Both Do delegates are executed and state == 1
Assert.That(state, Is.EqualTo(0));

其中IFoo

public interface IFoo
{
    void Bar();
}

缺少对NSubstitute API的更改,解决方法是:

var state = 0;
var substitute = Substitute.For<IFoo>();

Action<CallInfo>[] onBar = {c => state++};

substitute.When(s => s.Bar()).Do(c => onBar[0](c));
substitute.Bar();
Assert.That(state, Is.EqualTo(1));

onBar[0] = c => state--;
substitute.Bar();
Assert.That(state, Is.EqualTo(0));