Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When unit testing, how do I mock a return null from async method?

Normally, I mock my repo like so:

var repository = new Mock<ISRepository>();
repository.Setup(r => r.GetMemberAsync(email))
    .Returns(Task.FromResult(new Member
    {
        FirstName = firstName,
        LastName = lastName
    }));

But, in my code, I check to see if the member is not found, i.e. GetMemberAsync returns null. How do I mock this?

I tried:

var repository = new Mock<ISRepository>();
repository.Setup(r => r.GetMemberAsync(email))
    .Returns(Task.FromResult<object>(null));

but I get a compile error.

like image 605
ScubaSteve Avatar asked Oct 26 '15 22:10

ScubaSteve


People also ask

Can async method return null?

Task represents the execution of the asynchronous method, so for an asynchronous method to return a null task is like telling the calling code "you didn't really just call this method" when of course it did. So, a Task / Task<T> returned from a method should never, ever be null .

Can unit tests be async?

Unlike async void unit tests that are quite complicated, you can have async Task unit tests, i.e., unit tests that return a Task instance. Almost all the unit test frameworks (MSTest, NUnit, etc.) provide support for such unit tests.


3 Answers

You get a compiler error because you return a task that doesn't match the type the async method returns. You should return Task<Member> instead of simply Task<object>:

repository.Setup(r => r.GetMemberAsync(email)).Returns(Task.FromResult<Member>(null));
like image 79
i3arnon Avatar answered Oct 12 '22 10:10

i3arnon


It is also possible to return the result without using the Task class.

repository
    .Setup(r => r.GetMemberAsync(email))
    .ReturnsAsync((Member)null);
like image 35
Marcel Gelijk Avatar answered Oct 12 '22 10:10

Marcel Gelijk


Old question but you can also do this which I think it cleaner:

Assuming the default value of your object is null you can also use:

default(<insert object type here>)

e.g.

default(Member)
default(List<string>)
etc.

Full Example:

var myRepo = new Mock<IMyRepo>();
myRepo 
    .Setup(p => p.GetAsync("name"))
    .ReturnsAsync(default(List<string>));
like image 3
Percy Avatar answered Oct 12 '22 11:10

Percy