Dependency Injection: Turtles all the way down?

后端 未结 5 853
执笔经年
执笔经年 2020-12-01 18:11

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

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 18:52

    In order to use Dependency Injection, your classes would have their dependencies injected into them (several ways to do that - constructor injection, property injection) and would not instantiate them themselves, as you do in your examples.

    Additionally, one would extract the interface of each dependency to help with testability and use the interface instead of an implementation type as the dependency.

    class Foo
    {
        private IExternalDependency ed;
        public int doSomethingWithExternalDependency() {...}
    
        public Foo(IExternalDependency extdep)
        {
          ed = extdep;
        }
    }
    

    What most people do is use a mocking framework to mock the dependencies when testing.

    You can mock any object that the class under test depends on (including behavior and return values) - pass the mocks to the class as its dependencies.

    This allows you to test the class without relying on the behavior of its (implemented) dependencies.

    In some cases, you may want to use fakes or stubs instead of a mocking framework. See this article by Martin Fowler about the differences.


    As for getting all the dependencies, all the way down - one uses an IoC container. This is a registry of all of the dependencies in your system and understands how to instantiate each and every class with its dependencies.

提交回复
热议问题