When unit testing, how do I mock a return null from async method?
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));
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>));
It is also possible to return the result without using the Task class.
repository
.Setup(r => r.GetMemberAsync(email))
.ReturnsAsync((Member)null);