Home > Back-end >  How to mock a null response from a function delegate in c#
How to mock a null response from a function delegate in c#

Time:11-29

I have a function that I'm passing as a parameter like this:

public async Task<Number> MeasureAsync<Number>(Func<Task<Number>> sendFunc)
{
    //implementation
}

I want to test this function and test a case where the sendFunc returns null. In my unit test, I'm attempting to mock the sendFunc but I'm getting an error saying my mock is ambiguous. Here is my mock:

var functionMock = new Mock<Func<Task<Number>>>();

functionMock.Setup(x => x.Invoke()).ReturnsAsync(null); // error on ReturnsAsync because the call is ambiguous

Is there a way I'm supposed to specify the return type?

CodePudding user response:

looks like I was able to find a solution by specifying the type like so:

Number number = null;

functionMock.Setup(x => x.Invoke()).ReturnsAsync(number);

CodePudding user response:

You can choose from a handful of alternatives

functionMock.Setup(x => x.Invoke()).ReturnsAsync((Number)null);
functionMock.Setup(x => x.Invoke()).ReturnsAsync(default(Number));
functionMock.Setup(x => x.Invoke()).Returns(Task.FromResult<Number>(null));
functionMock.Setup(x => x.Invoke().Result).Returns(() => null);

and a several combinations of the above ones

  • Related