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

时间:2010-03-23 23:50:13

标签: c# unit-testing constructor-chaining

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

在“:this(...)”调用和反直觉调用默认构造函数中的参数化构造函数时,似乎有点丑陋的“新”事物,我想知道其他人会在这做什么?< / p>

(仅供参考 - &gt; 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...
}

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

这就是我的表现。

class MyUnitTestableClass
{
    public MyUnitTestableClass(IMockable foo)
    {
        // do stuff
    }

    public MyUnitTestableClass()
        : this(new DefaultImplementation())
    {
    }
}