依赖注入:乌龟一路下来?

guy*_*guy 16 unit-testing dependency-injection

所以我想知道单元测试在处理外部依赖关系方面是如何工作的.在这里和其他地方,我已经熟悉依赖注入,以及它如何允许我们测试代码的单元(A).但是,我对如何测试现在具有外部依赖性的其他单元(B和C)感到困惑,因此他们可以将它注入原始单元(A).

例如,假设一些类Foo使用外部依赖...

class Foo
{
    private ExternalDependency ed;
    public int doSomethingWithExternalDependency() {...}
}
Run Code Online (Sandbox Code Playgroud)

而且Bar使用Foo ...

class Bar
{
    public int doSomethingWithFoo
    {
        Foo f = new Foo();
        int x = f.doSomethingWithExternalDependency();
        // Do some more stuff ...
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我知道我可以使用依赖注入,以便我可以测试Foo,但是我如何测试Bar?我想,我可以再次使用依赖注入,但在某些时候某些单元需要实际创建外部依赖; 那我该怎么测试那个单位呢?

Mar*_*ann 16

您提供的示例不使用依赖注入.相反,Bar应该使用构造函数注入来获取Foo实例,但是注入具体类没有意义.相反,你应该从Foo中提取一个接口(让我们称之为IFoo)并将其注入Bar:

public class Bar
{
    private IFoo f;

    public Bar(IFoo f)
    {
        this.f = f;
    }

    public int doSomethingWithFoo
    {
        int x = this.f.doSomethingWithExternalDependency();
        // Do some more stuff ...
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

这使您可以始终分离消费者和依赖项.

是的,仍然有一个地方你必须编写整个应用程序的对象图.我们称这个地方为组合根.它是一个应用程序基础架构组件,因此您无需对其进行单元测试.

在大多数情况下,您应该考虑为该部件使用DI容器,然后应用Register Resolve Release模式.