c# - 为使用 RestClient 的实用程序编写单元测试
问题描述
我们决定创建一个可以跨多个项目重用的 HTTP 记录器,我们创建了一个如下所示的实用程序。
// pseudo-code
public class HttpLog{
private readonly string uri;
private readonly RestClient client;
public HttpLog(string uri){
this.uri = uri;
// notice the initialization of rest client
this.client = new RestClient();
}
void write(object data){
this.client.uri = this.uri + endpoint;
this.client.postAsync(data);
}
}
消费者应该提供 URI,我们已经公开了公共写入方法来记录数据,但是,我们无法对我们的HttpLog
类进行单元测试,因为它初始化了其余客户端。我们没有使用依赖注入,因为我们正在创建实用程序。
任何有关如何重构或单元测试的帮助将不胜感激。write()
方法。
我们可以想到两种方法
- 构造函数重载(这不是单元测试的有效方法)
- 将客户财产设为公共 {get; set} 这也违反了 OOP 原则。
请让我们知道是否有更好的方法来对此代码进行单元测试。
下面的答案说明使用构造函数重载或将属性公开
为什么我不喜欢依赖注入或构造函数重载,因为我坚信消费者/客户端不应该关心或担心实现细节。它们应该尽可能抽象。如果你让它们在构造函数重载中,那么你正在制造一种污染抽象的方法。
例如,如果您使用的是 RestClient 或 HttpClient,他们不会要求您提供有关如何写入数据的 HTTP 实现,他们只是要求您发布 URI 和数据,这对最终用户来说是真正的抽象。
请纠正我如果我的假设是错误的
解决方案
我们没有使用依赖注入,因为我们正在创建实用程序。
这不是一个原因。如果您使用依赖项并希望能够正确测试它,则应使用依赖项注入。这并不意味着您不能为普通用户提供默认实现。
提供构造函数重载。我不知道你为什么认为这会“低效”。
例子:
public class HttpLog{
private readonly string uri;
private readonly RestClient client;
public HttpLog(string uri) : this(uri, new RestClient()){
}
public HttpLog(string uri, RestClient restClient){
this.uri = uri;
// notice the initialization of rest client
this.client = restClient;
}
void write(object data){
this.client.uri = this.uri + endpoint;
this.client.postAsync(data);
}
}
推荐阅读
- python - 使用相同数据库的不同进程之间的数据竞争
- spring-boot - SpringBoot @DataJpaTest 抛出 Failed to load ApplicationContext 异常
- javascript - 您如何理解 WebStorm 的功能接口?
- python - Azure DevOps Pipeline 上没有日志记录
- react-native - 如何在本机反应中将视频(从移动存储)转换为base64?
- c# - 如何清除隐藏的字符?
- python - 转置数据框后如何按组绘制线条?
- go - 如何为 golang/go cmd 模块设置 VSCode?
- sysv-ipc - python sysv-ipc 创建/附加/删除共享内存
- r - 避免使用 data.table 循环