这个问题已经在这里有一个答案:
我写的测试情况下,我需要模拟得到同步的方法,请提供帮助。我们使用C#
我使用的测试案例
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
var mockClient = new Mock<HttpClient>();
mockClient.Setup(client => client.GetAsync(requestUri)).ReturnsAsync(response1);
但我正在逐渐无效设置例外
我会使用一个库如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));
随着new Mock<HttpClient>()
我相信你正在使用的起订量嘲讽,如果因此你不能嘲笑GetAsync()
同样因为起订量是允许只模拟abstract
或virtual
方法动态代理基于嘲讽系统。
你最好的选择将是创建一个HttpClient
适配器/包装和嘲笑,在这种情况下。就像是
public interface IHttpClient
{
HttpResponseMessage GetDataAsync(string uri);
}
然后,你可以嘲笑它说
var mockclient = new Mock<IHttpClient>();
mcokclient.Setup(x => x.GetDataAsync(It.IsAny<string>())).Returns(message);