When to use Dependency Injection

前端 未结 8 964
野性不改
野性不改 2020-12-01 00:19

I\'ve had a certain feeling these last couple of days that dependency-injection should really be called \"I can\'t make up my mind\"-pattern. I know this might sound silly,

8条回答
  •  一生所求
    2020-12-01 00:47

    Dependency Injection gives you the ability to test specific units of code in isolation.

    Say I have a class Foo for example that takes an instance of a class Bar in its constructor. One of the methods on Foo might check that a Property value of Bar is one which allows some other processing of Bar to take place.

    public class Foo
    {
        private Bar _bar;
    
        public Foo(Bar bar)
        {
            _bar = bar;
        }
    
        public bool IsPropertyOfBarValid()
        {
            return _bar.SomeProperty == PropertyEnum.ValidProperty;
        }
    }
    

    Now let's say that Bar is instantiated and it's Properties are set to data from some datasource in it's constructor. How might I go about testing the IsPropertyOfBarValid() method of Foo (ignoring the fact that this is an incredibly simple example)? Well, Foo is dependent on the instance of Bar passed in to the constructor, which in turn is dependent on the data from the datasource that it's properties are set to. What we would like to do is have some way of isolating Foo from the resources it depends upon so that we can test it in isolation

    This is where Dependency Injection comes in. What we want is to have some way of faking an instance of Bar passed to Foo such that we can control the properties set on this fake Bar and achieve what we set out to do, test that the implementation of IsPropertyOfBarValid() does what we expect it to do, i.e. return true when Bar.SomeProperty == PropertyEnum.ValidProperty and false for any other value.

    There are two types of fake object, Mocks and Stubs. Stubs provide input for the application under test so that the test can be performed on something else. Mocks on the other hand provide input to the test to decide on pass\fail.

    Martin Fowler has a great article on the difference between Mocks and Stubs

提交回复
热议问题