1

I understand that in order to facilitate the testing process, one should use dependency injection as a design principle. If I'm not wrong, instead of allocating an object I'm going to use, I should declare it as public and let someone else do the job; in this case when testing and creating the mock. However, in order to use the real object, eventually, I will have to allocate it. But, where?

I used lazy instantiation to allow the mock object to take place over the real one, and when it does't, when I'm running the app, the real object will be used. It gets the job done but I was told that it's not a good practice to use lazy instantiation in that way; specially, when the object to be allocated requires different parameters. For example, a NSURLConnection.

The class using the object is a ViewController, so it is the last "client". There's no other class that I can delegate the allocation of the object, and if I allocated it in, let's say, viewDidLoad then I won't be able to mock that object.

4

1 回答 1

1

这就是创建依赖注入 (DI) 容器的原因。他们负责在运行时创建对象的实例。当你正确连接它时,你不必为此在你的类中编写一行代码。通常,所有类都在其构造函数中声明它们的依赖关系。

public class SomeClass
{
    public SomeClass(ISomeDependency dependency)
    {
        //assing dependency to a field etc
    }
}

当您的应用程序需要创建SomeClass类型的实例时,它会将其委托给 DI 容器。容器将检查构造函数并发现它必须提供ISomeDependencyfirst 的实例。容器保存映射到抽象的具体类型的列表。这些列表是由代码、配置文件或某些约定创建的。当容器找到ISomeDependency接口的具体类型时,它会尝试以相同的方式创建它的实例。这一直持续到提供所有依赖项并且您获得SomeClass. 这些依赖项也可以很容易地被单元测试中的测试替身替换。

DI 容器是复杂的库,它们不仅仅是创建对象图。他们还管理他们创建的对象的生命周期。由于您还没有自己创建对象,因此您必须在不再需要时通知容器。为此,您的应用程序应该有第二个到容器的钩子。这些钩子特定于每个平台,您可以轻松找到连接流行容器的示例。

于 2013-07-12T13:37:07.390 回答