What do programmers mean when they say, “Code against an interface, not an object.”?

前端 未结 7 1845
情书的邮戳
情书的邮戳 2020-11-27 11:21

I\'ve started the very long and arduous quest to learn and apply TDD to my workflow. I\'m under the impression that TDD fits in very well with IoC principle

7条回答
  •  误落风尘
    2020-11-27 11:41

    Consider:

    class MyClass
    {
        //Implementation
        public void Foo() {}
    }
    
    class SomethingYouWantToTest
    {
        public bool MyMethod(MyClass c)
        {
            //Code you want to test
            c.Foo();
        }
    }
    

    Because MyMethod accepts only a MyClass, if you want to replace MyClass with a mock object in order to unit test, you can't. Better is to use an interface:

    interface IMyClass
    {
        void Foo();
    }
    
    class MyClass : IMyClass
    {
        //Implementation
        public void Foo() {}
    }
    
    class SomethingYouWantToTest
    {
        public bool MyMethod(IMyClass c)
        {
            //Code you want to test
            c.Foo();
        }
    }
    

    Now you can test MyMethod, because it uses only an interface, not a particular concrete implementation. Then you can implement that interface to create any kind of mock or fake that you want for test purposes. There are even libraries like Rhino Mocks' Rhino.Mocks.MockRepository.StrictMock(), which take any interface and build you a mock object on the fly.

提交回复
热议问题