Gradual approaches to dependency injection
        Posted  
        
            by 
                JW01
            
        on Programmers
        
        See other posts from Programmers
        
            or by JW01
        
        
        
        Published on 2011-01-29T20:00:19Z
        Indexed on 
            2011/01/29
            23:32 UTC
        
        
        Read the original article
        Hit count: 526
        
unit-testing
|dependency-injection
I'm working on making my classes unit-testable, using dependency injection. But some of these classes have a lot of clients, and I'm not ready to refactor all of them to start passing in the dependencies yet. So I'm trying to do it gradually; keeping the default dependencies for now, but allowing them to be overridden for testing.
One approach I'm conisdering is just moving all the "new" calls into their own methods, e.g.:
public MyObject createMyObject(args) {
  return new MyObject(args);
}
Then in my unit tests, I can just subclass this class, and override the create functions, so they create fake objects instead.
Is this a good approach? Are there any disadvantages?
More generally, is it okay to have hard-coded dependencies, as long as you can replace them for testing? I know the preferred approach is to explicitly require them in the constructor, and I'd like to get there eventually. But I'm wondering if this is a good first step.
© Programmers or respective owner