Stubbing object instantiation using PowerMock
In some badly written code, you can find cases in which the system under test's collaborators are not passed into the object in any way (for example, by the constructor), but the object itself instantiates them via the new
operator. The best practice would be to not write like this in the first place. But let's assume that you have inherited such a code and, since we follow the boy scout rule, that you should leave the code that you've encountered in a better state than you the one in which you have found it in the first place. We have to do something about this.
The very step of the refactoring of such a scenario is presented in Chapter 8, Refactoring with Mockito. This is why, in the current recipe, we will just learn how to stub object initialization in such a way that instead of creating a new instance of an object, a mock will be returned. Unfortunately, Mockito can't perform such stubbing, and that's why we will use PowerMock to do that...