2017-07-17 88 views
1

由於Improper Instantiation problem,建議創建private static readonlyHttpClient的實例。爲`private static readonly`字段創建存根

由於缺少時間,我已將mocked client注入測試方法,其中參數爲client

問題是我該如何以簡單的方式將mock注入private static readonly HttpClient字段SingleHttpClientInstanceController

+4

您應該使用IoC容器並將其配置爲始終傳遞單個實例。 – SLaks

+0

需要一些代碼 – hellboy

+0

瞭解IoC容器。確切的細節取決於你如何構建你的代碼。 – SLaks

回答

2

我簡單的方法怎麼能注入mockSingleHttpClientInstanceControllerprivate 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容器,請記住將訪問器註冊爲單例。