如何模拟Task <httpresponsemessage>的数据? C#

时间:2019-03-20 14:09:03

标签: c# unit-testing moq xunit

我正在尝试设置模拟功能,但无法返回正确的数据 我遇到了错误:

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);

1 个答案:

答案 0 :(得分:2)

使用ReturnsAsync返回Task<T>,请尝试以下操作:

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

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

相同