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

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

问题描述

所以我想知道单元测试在处理外部依赖项方面是如何工作的.在这里和其他地方,我已经熟悉依赖注入,以及它如何允许我们测试代码单元 (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() {...}
}

并且 Bar 类使用了 Foo...

And class Bar makes use off Foo...

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

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

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 应该使用 Constructor Injection 来获取 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天全站免登陆