Powerful singleton class using void method using PowerMockito

I keep getting WanterButNotInvoked exception in my UT with the below code:

@RunWith( PowerMockRunner.class )
@PrepareForTest( { CounterHandler.class, 
TrHandlerProtocolsCounterHandler.class, IProtocolCounterHandler.class } )

public void testInitialize() 
    IProtocolCounterHandler counter = new TrHandlerProtocolsCounterHandler();
    CounterHandler mockCounter = PowerMockito.spy( CounterHandler.getInstance() );
    PowerMockito.doNothing().when( mockCounter ).initialize();

    Mockito.verify( mockCounter ).initialize();


} ======================
CounterHandler class

public void initialize() {
    //do something


TrHandlerProtocolsCounterHandler class

public void initialize()  {


I debugged that Counterhandler.getInstance.initialize was executed, but when I try to test it, it says there was no layout interaction. Thank!


source to share

1 answer

The problem is that you created a new instance CounterHandler

that is the spy of the singleton instance. However, you haven't done anything to replace the singleton instance reference CounterHandler

with a class using this spy. So when your class calls getInstance

, it gets the actual instance, not the spy.

What you need to do is mock the call to the constructor so that the singleton instance is a mock. Read this article to show you how to do this and discuss alternatives to using Singleton.

Mocks one tunnel with EasyMock and PowerMock



All Articles