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

前端 未结 3 1154
面向向阳花
面向向阳花 2021-02-18 20:45

Normally, I mock my repo like so:

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


        
相关标签:
3条回答
  • 2021-02-18 20:55

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

    repository
        .Setup(r => r.GetMemberAsync(email))
        .ReturnsAsync((Member)null);
    
    0 讨论(0)
  • 2021-02-18 21:13

    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));
    
    0 讨论(0)
  • 2021-02-18 21:17

    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>));
    
    0 讨论(0)
提交回复
热议问题