NSubstitute - mock out parameter behaviour for any parameter
configProvider.TryGet("key1", out Arg.Any<string>())
is not valid C# syntax, which is why it wont compile.
You need to use an actual variable for the out parameter.
The following works when tested.
//Arrange
var expectedResult = true;
var expectedOut = "42";
var actualOut = "other";
var anyStringArg = Arg.Any<string>();
var key = "key1";
var configProvider = Substitute.For<IConfigurationProvider>();
configProvider
.TryGet(key, out anyStringArg)
.Returns(x => {
x[1] = expectedOut;
return expectedResult;
});
//Act
var actualResult = configProvider.TryGet(key, out actualOut);
//Assert
Assert.AreEqual(expectedOut, actualOut); // PASS.
Assert.AreEqual(expectedResult, actualResult); // PASS.
As of NSubstitute 4+ this is supported out the box:
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).
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);
Source
Make sure you note the argument index used above (x[1] = 42;
), this array includes the input and output variables but you can only set the value of an out
variable.