Thursday 6 September 2018

Mockito : Mock a method level local object




The method to be tested, which internally creates a local Object of MyOtherClass, which can not be set/mocked via Constructor

public class MyClass {
    public someReturn myMethod(){
        MyOtherClass otherClassObject = new MyOtherClass();
        boolean retBool = otherClassObject.otherClassMethod();
        if(retBool){
            // do something
        }
    }
}


So use power Mock, to say, whenever a new object with default contructor is called, use above object,
and you can add any other propery for your mocked object


@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)  //tells powerMock we will modify MyClass to intercept calls to new somewhere inside it
public class MyClassTest{
    @Test
    public void test(){
          MyOtherClass myMockOtherClass = createMock(MyOtherClass.class);
          //this will intercept calls to "new MyOtherClass()" in MyClass
          whenNew( MyOtherClass.class).withNoArguments().thenReturn( myMockOtherClass ) );          when(myMockOtherClass.otherClassMethod()).thenReturn(true);



   }
Ref : https://stackoverflow.com/questions/29398283/mocking-a-local-object-inside-a-method-of-sut-using-mockito-or-powermocktio?rq=1