这是使用构造函数链接的好方法还是坏方法?(......允许测试)

Gro*_*ile 6 c# unit-testing constructor-chaining

我在这里链接我的类构造函数的动机是,我有一个默认构造函数供我的应用程序主流使用,第二个允许我注入一个mock和一个stub.

在":this(...)"调用中看起来有点丑陋的"新"事物并且反直觉地从默认构造函数中调用参数化构造函数,我想知道其他人会在这做什么?

(仅供参考 - > SystemWrapper)

using SystemWrapper;

public class MyDirectoryWorker{

    //  SystemWrapper interface allows for stub of sealed .Net class.
    private IDirectoryInfoWrap dirInf;

    private FileSystemWatcher watcher;

    public MyDirectoryWorker()
        : this(
        new DirectoryInfoWrap(new DirectoryInfo(MyDirPath)),
        new FileSystemWatcher()) { }


    public MyDirectoryWorker(IDirectoryInfoWrap dirInf, FileSystemWatcher watcher)
    {
        this.dirInf = dirInf;
        if(!dirInf.Exists){
            dirInf.Create();
        }

        this.watcher = watcher;

        watcher.Path = dirInf.FullName;

        watcher.NotifyFilter = NotifyFilters.FileName;
        watcher.Created += new FileSystemEventHandler(watcher_Created);
        watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
        watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
        watcher.EnableRaisingEvents = true;
    }

    public static string MyDirPath{get{return Settings.Default.MyDefaultDirPath;}}

    // etc...
}
Run Code Online (Sandbox Code Playgroud)

Ber*_*rmo 3

包含默认构造函数是一种代码味道,因为现在该类已耦合到 IDirectoryInfoWrap 的具体实现。为了让您的生活更轻松,请使用类外部的 IOC 容器来注入不同的依赖项,具体取决于您运行的是测试代码还是主流应用程序。