我簡單的方法怎麼能注入mock
成SingleHttpClientInstanceController
private static readonly HttpClient
領域?
答:沒有簡單的方法。
建議:
摘要的訪問
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 };
}
}
同樣也應該用於訪問HttpContext
這是什麼Asp.Net核心的IHttpContextAccessor
的IHttpClientAcessor
的實現是最近推出的可以是這個樣子
public class HttpClientAccessor : IHttpClientAccessor {
static readonly Lazy<HttpClient> client = new Lazy<HttpClient>(() => new HttpClient());
public HttpClient HttpClient { get { return client.Value; } }
}
完成所以現在對於測試你可以注入依賴的模擬。
如果使用DI容器,請記住將訪問器註冊爲單例。
您應該使用IoC容器並將其配置爲始終傳遞單個實例。 – SLaks
需要一些代碼 – hellboy
瞭解IoC容器。確切的細節取決於你如何構建你的代碼。 – SLaks