This is how you’ll normally create substitutes for types. Generally this type will be an interface, but you can also substitute classes in cases of emergency.
Substituting for classes
var someClass =Substitute.For<SomeClassWithCtorArgs>(5,"hello world");
Substituting for multiple interfaces
There are times when you want to substitute for multiple types. The best example of this is when you have code that works with a type, then checks whether it implements IDisposable and disposes of it if it doesn’t.
var command =Substitute.For<ICommand,IDisposable>();var runner =newCommandRunner(command);runner.RunCommand();command.Received().Execute();((IDisposable)command).Received().Dispose();
Your substitute can implement several types this way, but remember you can only implement a maximum of one class. You can specify as many interfaces as you like, but only one of these can be a class. The most flexible way of creating substitutes for multiple types is using this overload:
var substitute =Substitute.For(new[]{typeof(ICommand),typeof(ISomeInterface),typeof(SomeClassWithCtorArgs)},newobject[]{5,"hello world"});Assert.IsInstanceOf<ICommand>(substitute);Assert.IsInstanceOf<ISomeInterface>(substitute);Assert.IsInstanceOf<SomeClassWithCtorArgs>(substitute);
Substituting for delegates
NSubstitute can also substitute for delegate types by using Substiute.For(). When substituting for delegate types you will not be able to get the substitute to implement additional interfaces or classes.
Setting a return value
The following examples relate to substituting for the following interface:
For methods
To set a return value for a method call on a substitute, call the method as normal, then follow it with a call to NSubstitute’s Returns() extension method.
This value will be returned every time this call is made. Returns() will only apply to this combination of arguments, so other calls to this method will return a default value instead.
For properties
The return value for a property can be set in the same was as for a method, using Returns(). You can also just use plain old property setters for read/write properties; they’ll behave just the way you expect them to.
Argument matchers
Argument matchers can be used when setting return values and when checking received calls. They provide a way to specify a call or group of calls, so that a return value can be set for all matching calls, or to check a matching call has been received.
The argument matchers syntax shown here depends on having C# 7.0 or later. If you are stuck on an earlier version (getting an error such as CS7085: By-reference return type 'ref T' is not supported while trying to use them) please use compatibility argument matchers instead.
Argument matchers should only be used when setting return values or checking received calls. Using Arg.Is or Arg.Any without a call to Returns(...) or Received() can cause your tests to behave in unexpected ways. See How NOT to use argument matchers for more information.
Ignoring arguments
An argument of type T can be ignored using Arg.Any<T>().
In this example we return 7 when adding any number to 5. We use Arg.Any<int>() to tell NSubstitute to ignore the first argument.
We can also use this to match any argument of a specific sub-type.
Conditionally matching an argument
An argument of type T can be conditionally matched using Arg.Is<T>(Predicate<T> condition).
If the condition throws an exception for an argument, then it will be assumed that the argument does not match. The exception itself will be swallowed.
Matching a specific argument
An argument of type T can be matched using Arg.Is<T>(T value).
This matcher normally isn’t required; most of the time we can just use 0 instead of Arg.Is(0). In some cases though, NSubstitute can’t work out which matcher applies to which argument (arg matchers are actually fuzzily matched; not passed directly to the function call). In these cases it will throw an AmbiguousArgumentsException and ask you to specify one or more additional argument matchers. In some cases you may have to explicitly use argument matchers for every argument.
Matching out and ref args
Argument matchers can also be used with out and ref (NSubstitute 4.0 and later with C# 7.0 and later).
var func = Substitute.For<Func<string>>();
func().Returns("hello");
Assert.AreEqual("hello", func());
public interface ICalculator {
int Add(int a, int b);
string Mode { get; set; }
}
var calculator = Substitute.For<ICalculator>();
calculator.Add(1, 2).Returns(3);
//Make a call return 3:
calculator.Add(1, 2).Returns(3);
Assert.AreEqual(calculator.Add(1, 2), 3);
Assert.AreEqual(calculator.Add(1, 2), 3);
//Call with different arguments does not return 3
Assert.AreNotEqual(calculator.Add(3, 6), 3);
calculator.Add(1, -10);
//Received call with first arg 1 and second arg less than 0:
calculator.Received().Add(1, Arg.Is<int>(x => x < 0));
//Received call with first arg 1 and second arg of -2, -5, or -10:
calculator
.Received()
.Add(1, Arg.Is<int>(x => new[] {-2,-5,-10}.Contains(x)));
//Did not receive call with first arg greater than 10:
calculator.DidNotReceive().Add(Arg.Is<int>(x => x > 10), -10);
formatter.Format(Arg.Is<string>(x => x.Length <= 10)).Returns("matched");
Assert.AreEqual("matched", formatter.Format("short"));
Assert.AreNotEqual("matched", formatter.Format("not matched, too long"));
// Will not match because trying to access .Length on null will throw an exception when testing
// our condition. NSubstitute will assume it does not match and swallow the exception.
Assert.AreNotEqual("matched", formatter.Format(null));
calculator.Add(0, 42);
//This won't work; NSubstitute isn't sure which arg the matcher applies to:
//calculator.Received().Add(0, Arg.Any<int>());
calculator.Received().Add(Arg.Is(0), Arg.Any<int>());
calculator
.LoadMemory(1, out Arg.Any<int>())
.Returns(x => {
x[1] = 42;
return true;
});
var hasEntry = calculator.LoadMemory(1, out var memoryValue);
Assert.AreEqual(true, hasEntry);
Assert.AreEqual(42, memoryValue);