Search code examples
unit-testingdependency-injectioninversion-of-control

Should you NEVER create a new object of any other class in another class' method?


I have been trying to understand Dependency injection and Ioc and all related concepts to it, but have not made much progress.

What I have understood is to make my class (say A) testable (my class which uses object of class B), I should have the object injected into my class' constructor like this:

class A{

    B class_B_Object;

    A(B class_B_Object){
        this.class_B_Object = class_B_Object;
    }
}

So, my question here is, is it safe to say that I should never have something like var classBObject = new B() in any of my class A's methods?


Solution

  • Never is a very strong word, and you should use it very carefully. Depending on what A and B are, it may be perfectly normal for A to create (and usually return) an instance of B. The main point of testability here is that if A uses an instance of B and relies on its logic, you should probably have an easy way to inject a mock instance of B where this logic is controlled (i.e. - mocked away), so when you write a unit test for A you're just testing its logic, not the underlying logic of B.