Yun*_*una 3 java singleton junit4 mockito powermock
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 it, it says that there were no interactions with the mock. Thanks!
The problem here is that you have created a new instance of CounterHandler that is the spy of the singleton instance. However, you have done nothing to replace the singleton instance help by the CounterHandler class with this spy. Therefore when your class calls getInstance it gets the actual instance, not the spy.
What you need to do is mock the constructor call so that the singleton instance is a mock. Read this article which shows how to do it and provides a discussion of alternatives to using Singleton.
Mocking a singleton with EasyMock and PowerMock
| 归档时间: |
|
| 查看次数: |
7648 次 |
| 最近记录: |