Search code examples
c#nsubstitute

Returns delegate function NSubstitute


I am trying to test a delegate function using NSubstitute:

_myMock.CallDelegateIfKeyMissing(Arg.Any<string>, Arg.Any<Func<Task<string>>>())
.Returns(
   //The results of the delegate function "Arg.Any<Func<Task<string>>>"
);

Is this possible please? Thank you


Solution

  • You can access the Func<Task<string>> argument from within the Returns and invoke it:

    _myMock
        .CallDelegateIfKeyMissing(Arg.Any<string>(), Arg.Any<Func<Task<string>>>())
        .Returns(
            x => x.Arg<Func<Task<string>>>().Invoke()
        );
    
    var result = _myMock.CallDelegateIfKeyMissing("hi", () => Task.FromResult("world"));
    
    Assert.Equal("world", result.Result);
    

    There's a bit more information in the NSubstitute documentation.