简体   繁体   中英

Mocking of Singleton Public/Void method failing with PowerMockito

So here is the Scenario :

public class classA implements classRandom {
   public void methodA(arg1, arg2) {
       POJOb objB;
       objB = SingletonClass_Instance().singletonMethodA(arg1);
   }
   public SingletonClass SingletonClass_Instance() {
       return SingletonClass.getInstance();
   }
}

public class SingletonClass {
    public objB singletonMethodA(final String arg1) {
        return randomObj;
    }
}

I am writing a unit test for methodA in Class A. For this i have written the following stub code:

SingletonClass mockSingletonClass = PowerMockito.mock(SingletonClass.class);
POJOb = PowerMockito.mock(POJOb.class);
Mockito.when(mockSingletonClass.singletonMethodA(Mockito.anyString())).thenReturn(POJOb);

Now immediately after this code, i have a code:

POJOb objB = classA_Object.methodA(arg1, arg2);

This code fails as soon as it reaches:

**methodA -->  SingletonClass_Instance().singletonMethodA**

I have already used the following Powermockito procedures:

1) import PM libs
2) Added @PrepareForTest({SingletonClass.class, POJOb.class})

Still i am unable to mock the Public/Void methods of SingletonClass. They are always coming out to be null.

You'll need to do something like this.

PowerMockito.mockStatic(SingletonClass.class);
SingletonClass mockSingleton = PowerMockito.mock(SingletonClass.class);
PowerMockito.when(SingletonClass.getInstance()).thenReturn(mockSingleton);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM