- 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
Throwing exceptions
The Throws
and ThrowsAsync
helpers in the NSubstitute.ExceptionExtensions
namespace can be used to throw exceptions when a member is called.
//For non-voids:
calculator.Add(-1, -1).Throws(new Exception()); // Or .Throws<Exception>()
//For voids and non-voids:
calculator
.When(x => x.Add(-2, -2))
.Throw(x => new Exception()); // Or .Throw<Exception>() - - don't use .Throw*s* in this case
//Both calls will now throw.
Assert.Throws<Exception>(() => calculator.Add(-1, -1));
Assert.Throws<Exception>(() => calculator.Add(-2, -2));
Returns
Another way is to use the underlying method, .Returns
. See also Callbacks.
//For non-voids:
calculator.Add(-1, -1).Returns(x => { throw new Exception(); });
//For voids and non-voids:
calculator
.When(x => x.Add(-2, -2))
.Do(x => { throw new Exception(); });
//Both calls will now throw.
Assert.Throws<Exception>(() => calculator.Add(-1, -1));
Assert.Throws<Exception>(() => calculator.Add(-2, -2));