- Getting started
- Creating a substitute
- Setting a return value
- Return for specific args
- Return for any args
- Return from a function
- Multiple return values
- Replacing return values
- Checking received calls
- Clearing received calls
- Argument matchers
- Callbacks, void calls and When..Do
- Throwing exceptions
- Safe configuration and overlapping calls
- Raising events
- Auto and recursive mocks
- Setting out and ref args
- Actions with argument matchers
- Checking call order
- Partial subs and test spies
- Return for all calls of a type
- Threading
- Compatibility argument matchers
- NSubstitute.Analyzers
- How NSubstitute works
- Search
Checking call order
Sometimes calls need to be made in a specific order. Depending on the timing of calls like this is known as temporal coupling. Ideally we’d change our design to remove this coupling, but for times when we can’t NSubstitute lets us resort to asserting the order of calls.
[Test]
public void TestCommandRunWhileConnectionIsOpen() {
var connection = Substitute.For<IConnection>();
var command = Substitute.For<ICommand>();
var subject = new Controller(connection, command);
subject.DoStuff();
Received.InOrder(() => {
connection.Open();
command.Run(connection);
connection.Close();
});
}
If the calls were received in a different order then Received.InOrder
will throw an exception and show the expected and actual calls.
We can use standard argument matchers to match calls, just as we would when checking for a single received call.
[Test]
public void SubscribeToEventBeforeOpeningConnection() {
var connection = Substitute.For<IConnection>();
connection.SomethingHappened += () => { /* some event handler */ };
connection.Open();
Received.InOrder(() => {
connection.SomethingHappened += Arg.Any<Action>();
connection.Open();
});
}