Refactoring for unit testing
When you write in TDD, your code is unit testable from the first moment. This is because you took into consideration DI scenarios. Brownfield code almost always has no consideration for DI, and it will have to change to accommodate it.
In this section, we will cover the scenarios that you have to change, and then we will go through an example of a sample refactoring at the end of this section.
Variables instantiated in the code
Whenever you see a new
keyword in the code that is instantiating a library or a service, then most probably, this needs refactoring. Take the following example of code in a method:
var obj = new Foo(); obj.DoBar();
The previous line means we cannot inject a test double for Foo
, so the code needs to change to inject it.
The next thing to do is to check whether Foo
implements an interface for the methods you are using from this class. Let me break the bad news for you here – keep your expectations low; you...