Moq 不包含 ReturnAsync 的定义?

Nil*_*min 11 .net c# unit-testing moq

我正在尝试模拟对第三方服务的一些 API 调用以进行单元测试。我真的只是希望这个模拟函数RestEase.Response<...>每次都返回相同的值。

// Setup
var VeracrossMock = new Mock<IVeracrossAPI>(MockBehavior.Strict);
Func<List<VeracrossStudent>> func = () => new List<VeracrossStudent>() { new VeracrossStudent() { First_name = "Bob", Last_name = "Lob" } };
RestEase.Response<List<VeracrossStudent>> resp = new RestEase.Response<List<VeracrossStudent>>("", new HttpResponseMessage(HttpStatusCode.OK), func);

// Problem is on the line below
VeracrossMock.Setup(api => api.GetStudentsAsync(1, null, CancellationToken.None)).ReturnsAsync<RestEase.Response<List<VeracrossStudent>>>(resp);
Run Code Online (Sandbox Code Playgroud)

它给了我一个红色下划线,然后声称ReturnsAsync不存在,或者至少不存在我给出的论点。

Error CS1929 'ISetup<IVeracrossAPI, Task<Response<List<VeracrossStudent>>>>' does not contain a definition for 'ReturnsAsync' and the best extension method overload 'SequenceExtensions.ReturnsAsync<Response<List<VeracrossStudent>>>(ISetupSequentialResult<Task<Response<List<VeracrossStudent>>>>, Response<List<VeracrossStudent>>)' requires a receiver of type 'ISetupSequentialResult<Task<Response<List<VeracrossStudent>>>>'
Run Code Online (Sandbox Code Playgroud)

我应该如何使用ReturnsAsync?不知道如何嘲笑这个。

zap*_*ppa 13

在过去的几周里,我多次遇到此错误消息,但一直忘记如何修复它,因此我将其写在这里,希望它对某人有所帮助。每次都是因为我很愚蠢,当我设置的方法需要一个对象/类型列表时,我正在传递一个对象/类型。

  • 在过去的几周里,我多次遇到此错误消息,但一直忘记如何修复它,因此我将其写在这里,希望它对某人有所帮助。每次都是因为我很愚蠢,当我设置的方法返回 List&lt;T&gt; 时,我返回了 IEnumerable&lt;T&gt; 。 (5认同)
  • 已重构,模拟返回一个列表,但新方法仅返回一个项目。有史以来最糟糕的错误消息... (2认同)

Nko*_*osi 12

正在使用的泛型参数与被模拟成员的参数不匹配。

删除泛型参数

VeracrossMock
    .Setup(_ => _.GetStudentsAsync(1, null, CancellationToken.None))
    .ReturnsAsync(resp);
Run Code Online (Sandbox Code Playgroud)

并且该方法将根据被模拟的成员推断所需的通用参数。


Yon*_*Nir 7

此错误的另一个选项是因为ReturnsAsync仅适用于返回Task<T>. 对于仅返回任务的方法,可以使用以下选项之一:

mock.Setup(arg=>arg.DoSomethingAsync()).Returns(Task.FromResult(default(object)))


mock.Setup(arg=>arg.DoSomethingAsync()).Returns(Task.CompletedTask);
Run Code Online (Sandbox Code Playgroud)