依赖注射:海龟一路下来? [英] Dependency Injection: Turtles all the way down?

查看:106
本文介绍了依赖注射:海龟一路下来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想知道单元测试在处理外部依赖方面是如何工作的。在这里和其他地方,我已经熟悉依赖注入,以及如何让我们测试代码单元(A)。然而,我对如何测试其他单位(B和C)感到困惑,这些单位现在拥有外部依赖关系,以便将其注入原始单位(A)。

So I'm wondering about how unit testing works in regards to dealing external dependencies. Here and elsewhere I've become familiar with dependency injection, and how that allows us to test a unit (A) of code. However, I'm confused about how to test other units (B and C) which are now possess the external dependency so they can inject it into the original unit (A).

例如,说一些类 Foo 使用外部依赖关系...

For example, say some class Foo uses an external dependency...

class Foo
{
    private ExternalDependency ed;
    public int doSomethingWithExternalDependency() {...}
}

和类使用 Foo ...

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

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

Now, I know that I can use dependency injection so that I can test Foo, but then how do I test Bar? I guess, I can, again, use dependency injection, but at some point some unit needs to actually create the external dependency; so how do I test that unit?

推荐答案

你提供的例子不使用依赖注入。相反,Bar应该使用构造函数注入来获取一个Foo实例,但注入具体的类没有任何意义。相反,你应该从Foo(我们称之为IFoo)中提取一个界面,并将其注入到Bar中:

The examples you provide do not use Dependency Injection. Instead, Bar should use Constructor Injection to get a Foo instance, but there's no point in injecting a concrete class. Instead, you should extract an interface from Foo (let's call it IFoo) and inject that into 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;
    }
}

这使您始终解除消费者和依赖关系

是的,仍然会有一个地方必须编写整个应用程序的对象图。我们称这个地方为构成根。这是一个应用程序基础结构组件,因此您不需要单元测试。

Yes, there will still be a place where you must compose the entire application's object graph. We call this place the Composition Root. It's a application infrastructure component, so you don't need to unit test it.

在大多数情况下,您应考虑使用 DI容器,然后应用注册解析版本模式

In most cases you should consider using a DI Container for that part, and then apply the Register Resolve Release pattern.

这篇关于依赖注射:海龟一路下来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆