小编Yun*_*una的帖子

Mock singleton class with void method using PowerMockito

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

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

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

    counter.initialize();
    Mockito.verify( mockCounter ).initialize();
Run Code Online (Sandbox Code Playgroud)

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

public void initialize() {
    //do something
}
Run Code Online (Sandbox Code Playgroud)

======================
TrHandlerProtocolsCounterHandler class

@Override
public void initialize()  {
    CounterHandler.getInstance().initialize();
}
Run Code Online (Sandbox Code Playgroud)


I have debugged that Counterhandler.getInstance.initialize was executed but when im trying to verify …

java singleton junit4 mockito powermock

3
推荐指数
1
解决办法
7648
查看次数

标签 统计

java ×1

junit4 ×1

mockito ×1

powermock ×1

singleton ×1