由于Improper Instantiation problem,建议您创建private static readonly
的{{1}}个实例。
由于时间不够,我已将mocked
client注入测试方法,并以HttpClient
为参数。
问题是如何以简单的方式将client
注入mock
的{{1}}字段?
答案 0 :(得分:2)
我怎样才能以简单的方式将
mock
注入private static readonly HttpClient
的{{1}}字段?
答:没有简单的方法。
建议:
摘要访问者背后的资源
SingleHttpClientInstanceController
并将其注入从属控制器。
public interface IHttpClientAccessor {
HttpClient HttpClient { get; }
}
访问public class SingleHttpClientInstanceController : ApiController {
private readonly HttpClient HttpClient;
public SingleHttpClientInstanceController(IHttpClientAccessor httpClientAccessor) {
HttpClient = httpClientAccessor.HttpClient;
}
// This method uses the shared instance of HttpClient for every call to GetProductAsync.
public async Task<Product> GetProductAsync(string id) {
var hostName = HttpContext.Current.Request.Url.Host;
var result = await HttpClient.GetStringAsync(string.Format("http://{0}:8080/api/...", hostName));
return new Product { Name = result };
}
}
同样也应该这样做,这是最近在Asp.Net-Core&#39; s HttpContext
IHttpContextAccessor
的实现可能看起来像这样
IHttpClientAcessor
所以现在对于测试你可以注入依赖的模拟。
如果使用DI容器,请记住将访问者注册为单身。