PowerMockito calls a method when I use doReturn (..). When (....)

I am new to PowerMockito, and there the behavior that I show I do not understand. The following code explains my problem:

public class ClassOfInterest {

  private Object methodIWantToMock(String x) {

    String y = x.trim();

    //Do some other stuff;
  }

  public void methodUsingThePrivateMethod() {

    Object a = new Object();
    Object b = methodIWantToMock("some string");

    //Do some other stuff ...
  }
}

I have a class that contains a private method that I want to mock under the name methodIWantToMock(String x). In my test code, I do the following:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassOfInterest.class)
public class ClassOfInterestTest {

  @Test
  public void someTestMethod() {

  ClassOfInterest coiSpy = PowerMockito.spy(new ClassOfInterest());

  PowerMockito.doReturn(null).when(coiSpy, "methodIWantToMock", any(String.class));

  coiSpy.methodUsingThePrivateMethod();

  //Do some stuff ...

  }
}

PowerMockito , methodIWantToMock methodUsingThePrivateMethod(), . , : PowerMockito.doReturn(...).when(...), PowerMockito methodIWantToMock !! ? , , coiSpy.methodUsingThePrivateMethod();.

0
1

, , . spy mock, PowerMockito , methodUsingThePrivateMethod() . , , mock spy. , PowerMockito , PowerMockito.doReturn(...).when(...). . , /, :

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassOfInterest.class)
public class ClassOfInterestTest {

  @Test
  public void someTestMethod() {

  //Line changed:
  ClassOfInterest coiMock = PowerMockito.mock(new ClassOfInterest());

  //Line changed:
  PowerMockito.doReturn(null).when(coiMock, "methodIWantToMock", any(String.class));

  //Line added:
  PowerMockito.when(coiMock.methodUsingThePrivateMethod()).thenCallRealMethod();

  coiSpy.methodUsingThePrivateMethod();

  //Do some stuff ...

  }
}
+2

Source: https://habr.com/ru/post/1583807/


All Articles