Moq with Task await

后端 未结 3 684
滥情空心
滥情空心 2021-02-03 17:43

Since I have converted my WCF methods to Async, my unit tests have failed, and I can\'t figure out the correct syntax to get them to work.

Cllient proxy class

相关标签:
3条回答
  • 2021-02-03 17:58

    DoSomething returns null instead of returning a Task, and so you get an exception when awaiting it. You need to specify when building the mock that it should return a Task.

    In this case it seems that you can simply return an already completed task using Task.FromResult so the mock setup should look like this:

    this._mockService.Setup(...).Returns(Task.FromResult(false));
    

    Beginning with the next version of .Net (4.6) you can use Task.CompletedTask like this:

    this._mockService.Setup(...).Returns(Task.CompletedTask);
    
    0 讨论(0)
  • 2021-02-03 18:14

    You can reduce the amount of clutter in the code by using ReturnsAsync

    this._mockService.Setup(...).ReturnsAsync(false);

    This way you can remove the Task.FromResult part of the code

    0 讨论(0)
  • 2021-02-03 18:25

    I think you need to return the Task from the DoSomething mock

    this._mockService.Setup(x => x.DoSomething(It.IsAny<CredentialDataList>(), It.IsAny<string>()))
        .Returns(Task.FromResult<int>(0));
    
    0 讨论(0)
提交回复
热议问题