如何模拟Task的数据 ? C#

问题描述 投票:1回答:1

我正在尝试设置模拟函数,但我无法返回正确的数据我得到的错误:

Error CS1503 Argument 1: cannot convert from 'System.Net.Http.HttpResponseMessage' to 'System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>'

这是我试图模拟的界面

public interface ICouchDbClients
{
    Task<HttpResponseMessage> AuthenticatedQuery(Func<Task<HttpResponseMessage>> query, string name, HttpClient client);
}

这是我尝试的设置

var httpResponseMessage = new HttpResponseMessage
{
   StatusCode = HttpStatusCode.Created
};

mockStateFixture.MockCouchDbClient.Setup(x => x.AuthenticatedQuery(
    It.IsAny<Func<Task<HttpResponseMessage>>>(),
    NamedHttpClients.COUCHDB,
    httpClient))
    .Returns(httpResponseMessage);
c# unit-testing moq xunit
1个回答
2
投票

使用ReturnsAsync返回Task<T>,试试这个:

mockStateFixture.MockCouchDbClient.Setup(x => x.AuthenticatedQuery(
    It.IsAny<Func<Task<HttpResponseMessage>>>(),
    NamedHttpClients.COUCHDB,
    httpClient))
    .ReturnsAsync(httpResponseMessage);

它实际上与Returns(Task.FromResult(httpResponseMessage))相同

© www.soinside.com 2019 - 2024. All rights reserved.