Using PowerMockito and Mockito to test calling another artifact method

I am sure that this is a fairly common question now, but I really can not get rid of this problem that I experience with a mocking private method that internally calls another method and returns a collection. The class I'm testing has a public method that calls a private method to get the Collection object. I use PowerMock to create a private method spy.

public void method1(String s)
{
     Collection<Object> list = invokePrivate()
}

private Collection<Object> invokePrivate()
{
     Wrapper wrapperObj = Factory.getInstance.getWrapper();
     Collection<Object> list = wrapperObj.callWrapperMethod(); // This always calls into real method, instead of mocked version.
     return list;
}

Test Class-:

So, to test the public method1 method, I create a spy using PowerMockito to spy on a private method and return a demo list.

MainClass obj = new MainClass();
MainClass spy = PowerMockito.spy(obj);
PowerMockito.when(spy, method(MainClass.class, "inokePrivate"))
                            .thenReturn(list); // demo list which exists as a test class member.

, wrapperObj.callWrapperMethod(), , . wrapperObj.callWrapperMethod.

WrapperClass wr = new WrapperClass();
WrapperClass spy1 = PowerMockito.spy(wr);
when(spy1.callWrapperMethod()).thenReturn(list) // demo list which exists as a test class member.

callWrapperMethod() . ?

, -:

Mockito: ,

mockito

[UPDATE] -: , :

PowerMockito.doReturn(list).when(spy1).callWrapperMethod(); // This returns me demo list successfully.

, PowerMockito, invokePrivate callWrapperMethod spy.

+4
1

. singleton factory .

"" ; "" ; , .

, . - :

class YourClass {
  private final Factory factory;

  public YourClass() {
     this(Factory.getInstance(); }

  YourClass(Factory theFactory) {
     this.factory = theFactory;
  ...

unit test; ( ) factory . , PowerMock.

- ; ; . - .

: "" (http://en.wikipedia.org/wiki/Law_of_Demeter): ; -; , factory; factory. ... , - . , , .

+2

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


All Articles