Question

Is it possible with NSubstitute to clear or remove a previous .When().Do() configuration?

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
Était-ce utile?

La solution

Looking at the source for the CallActions, there doesn't appear to be a way to remove or replace a callback.

Using an example proving the lack of replace functionality

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));

where IFoo is

public interface IFoo
{
    void Bar();
}

Lacking a change to the NSubstitute API, a workaround is:

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));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top