0
votes

I am writing down jUnit for legacy code. Scenario is as below:

Class A{
     B b;

     public void testMe(){
          b= new B(1,2,3);
     }
 }

is there any way to mock or override b with object created by me with customer params.

Yes, by using reflection. There's a built-in way to do this with Mockito using @InjectMocks. stackoverflow.com/questions/16467685/… - Christopher Schneider
@ChristopherSchneider thanks, that worked. but what if initialisation in happening inside method. That mock value is getting override by the initialisation. - Atul Kumar
Not without changing at least some of the legacy code. Option 1: inject a factory into A which knows how to create instances of B. The test injects a mock factory which can provide a mock B. Option 2 (ugly): extract b= new B(1,2,3) to a protected method. @Spy the instance being tested, and override that protected method to provide a mock B. - Andrew S