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

非 Y 不嫁゛ 提交于 2020-12-29 08:59:30

问题


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.


回答1:


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));



回答2:


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

repository
    .Setup(r => r.GetMemberAsync(email))
    .ReturnsAsync((Member)null);



回答3:


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>));


来源:https://stackoverflow.com/questions/33356808/when-unit-testing-how-do-i-mock-a-return-null-from-async-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!