如何模拟httpclient.getasync方法

时间:2019-02-05 11:50:15

标签: c# asp.net-web-api

我正在编写测试用例,我需要模拟获取同步方法 请提供帮助。我们正在使用c#

我正在使用测试用例

HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
var mockClient = new Mock<HttpClient>();
mockClient.Setup(client => client.GetAsync(requestUri)).ReturnsAsync(response1);

但是我收到无效的设置异常

2 个答案:

答案 0 :(得分:1)

我将使用诸如RichardSzalay.MockHttp(https://github.com/richardszalay/mockhttp)之类的库来创建HttpClient对象。例如:

// Create the mock
var mockHttp = new MockHttpMessageHandler();

// Setup the responses and or expectations
// This will return the specified response when the httpClient.GetAsync("http://localhost/api/user/5") is called on the injected object.
var request = mockHttp.When("http://localhost/api/user/*")
        .Respond("application/json", "{'name' : 'Test McGee'}"); // Respond with JSON

// Inject the handler or client into your application code
var client = mockHttp.ToHttpClient();

// Test code

// perform assertions
Assert.AreEqual(1, mockHttp.GetMatchCount(request));

答案 1 :(得分:0)

使用new Mock<HttpClient>(),我相信您正在使用 MOQ 进行模拟,如果这样,您将无法模拟GetAsync(),因为MOQ是动态代理基于的模拟系统,仅允许模拟abstractvirtual方法。

您最好的选择是为HttpClient创建一个适配器/包装器,并在这种情况下进行模拟。像

public interface IHttpClient
{
  HttpResponseMessage GetDataAsync(string uri);
}

然后您可以嘲笑它

var mockclient = new Mock<IHttpClient>();
mcokclient.Setup(x => x.GetDataAsync(It.IsAny<string>())).Returns(message);