C# 通过依赖注入进行日志记录与通过单元测试进行隐式依赖
我有一个类需要使用Log4net进行日志记录。下面是考虑单元测试的两种可能的解决方案 解决方案1:C# 通过依赖注入进行日志记录与通过单元测试进行隐式依赖,c#,log4net,C#,Log4net,我有一个类需要使用Log4net进行日志记录。下面是考虑单元测试的两种可能的解决方案 解决方案1: public class Car{ ILog log; public Car(ILog log){ this.log = log } //use logging for other methods } 解决方案2: public class Car ILog log = LogManager.GetLogger(typeof(Car)); public Car()
public class Car{
ILog log;
public Car(ILog log){
this.log = log
}
//use logging for other methods
}
解决方案2:
public class Car
ILog log = LogManager.GetLogger(typeof(Car));
public Car(){
}
//use logging for other methods
}
问题:
1) 一般来说哪种方式更好
2) 对于解决方案2,我应该如何在单元测试中替换记录器。您使用的是静态工厂(LogManager),但非静态工厂可能更好。然后您可以传入工厂本身,单元测试可以使用它创建自己的ILog对象。这使得嘲笑更容易
您仍然需要一种方法来创建工厂,但您可以通过检测测试版本来帮助进行测试。如何更好?对我来说,这似乎是一个意见问题。我已经看到了这两种方法,我相信每个作者都认为他们的方法是最好的。使用Ctor依赖注入很容易理解和使用。但它的下载端是为每个实例化传递它。使用隐式依赖关系可能会带来惊喜。