我有一个处理器来处理对端点的调用并返回响应。方法如下所示
public Event GetEvent()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://www.test.com");
HttpResponseMessage response = client.GetAsync("/event").GetAwaiter().GetResult();
var content = response.Content.ReadAsStringAsync().Result;
Event newEvent = JsonConvert.DeserializeObject<Event>(content);
response.EnsureSuccessStatusCode();
return newEvent;
}
现在我需要为这个类创建一个单元测试,它实际上不会向端点发出请求。我的单元测试遵循这种模式:
public HttpClientProcessorTest()
{
InstantiateClassUnderTest();
}
[Fact]
public void HttpClientProcessor_GetEvent_EnsuresSuccessfulStatusCodeAndReturnsEvent()
{
ShimHttpClient.AllInstances.GetAsync = (x) =>
{
};
ClassUnderTest.GetEvent();
}
但是我收到错误'ShimHttpClient.AllInstances' does not contain a definition for 'GetAsync'
。我将System.Net.Http添加到引用中,右键单击并添加了fakes程序集,但它只提供对某些方法的访问,而不是GetAsync()
。我省略了断言,因为在我甚至可以使垫片工作之前不需要它们。
如何填充GetAsync()?
答案 0 :(得分:1)
我是这样实现的:
代码:
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
Task<HttpResponseMessage> httpRequest = httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
HttpResponseMessage httpResponse = httpRequest.Result;
在测试中:
ShimHttpClient.AllInstances.SendAsyncHttpRequestMessageHttpCompletionOptionCancellationToken = (r,a, message, s) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));