我试图模拟一些对第三方服务的API调用,以进行单元测试。我真的只是想让这个 mock 的函数每次都返回相同的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);
它给了我一个红色的下划线,然后声称
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>>>>'
我应该如何使用
ReturnsAsync
?关于如何 mock 这一点一无所知。 最佳答案
使用的泛型参数与要模拟的成员的参数不匹配。
删除通用参数
VeracrossMock
.Setup(_ => _.GetStudentsAsync(1, null, CancellationToken.None))
.ReturnsAsync(resp);
并且该方法将根据被模拟的成员来推断所需的通用参数。