为“私有静态只读"字段创建存根 [英] Creating stub for `private static readonly` field

查看:83
本文介绍了为“私有静态只读"字段创建存根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不正确的实例化问题上到期建议创建HttpClientprivate static readonly实例.

Due on Improper Instantiation problem it is recommended to create private static readonly instance of HttpClient.

由于时间不足,我已将 mocked客户端注入到测试方法中, c3>作为其参数.

Due on lack of time I have injected mocked client into test method with client as their parameter.

问题是如何以简单的方式将mock注入到SingleHttpClientInstanceControllerprivate static readonly HttpClient字段中?

The problem is how can I in simple way inject mock into private static readonly HttpClient field of SingleHttpClientInstanceController?

推荐答案

如何以简单的方式将mock注入到SingleHttpClientInstanceControllerprivate static readonly HttpClient字段中?

how can I in simple way inject mock into private static readonly HttpClient field of SingleHttpClientInstanceController?

答案:没有简单的方法.

Answer: There is no simple way.

建议:

提取访问器背后的资源

public interface IHttpClientAccessor {
    HttpClient HttpClient { get; }
}

并将其注入到依赖控制器中.

and inject that into the dependent controller.

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-Core的IHttpContextAccessor

The same should also be done for accessing HttpContext which is what was recently introduced in Asp.Net-Core's IHttpContextAccessor

IHttpClientAcessor的实现可以看起来像这样

An implementation of the IHttpClientAcessor can look something like this

public class HttpClientAccessor : IHttpClientAccessor {
    static readonly Lazy<HttpClient> client = new Lazy<HttpClient>(() => new HttpClient());
    public HttpClient HttpClient { get { return client.Value; } }
}

所以现在对于测试,您可以注入依赖项的模拟.

So now for tests you can inject mock of the dependency.

如果使用DI容器,请记住也将访问者注册为单例.

If using a DI container remember to register the accessor as a singleton as well.

这篇关于为“私有静态只读"字段创建存根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆