为“private static readonly”字段创建存根

时间:2017-07-17 19:58:43

标签: c# unit-testing mocking inversion-of-control ioc-container

由于Improper Instantiation problem,建议您创建private static readonly的{​​{1}}个实例。

由于时间不够,我已将mocked client注入测试方法,并以HttpClient为参数。

问题是如何以简单的方式将client注入mock的{​​{1}}字段?

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容器,请记住将访问者注册为单身。