I have a problem similar to
http://groups.google.com/group/powermock/t/95f6c783f90fe843
I want to test a singleton lazy initialization.
Here's my singleton
public class BadInitializer {
private static BadInitializer instance;
public static BadInitializer getInstance() {
if (instance == null) {
instance = new BadInitializer();
}
return instance;
}
private BadInitializer() {
System.out.println("Initialized on : " + new Date());
}
}
I want to test that my object is only initialized once, which I doubt
for concurrent calls to getInstance()
@RunWith(PowerMockRunner.class)
@PrepareForTest( BadInitializer.class )
public class TestBadInitializer {
@Test
public void testOnlyInitializedOnce() throws Exception {
BadInitializer.getInstance();
verifyNew(BadInitializer.class).withNoArguments();
}
}
I expect this code to succeed, and then fail when I replace
BadInitializer.getInstance() with some kind of
callGetInstanceWithConcurrentThreads() implementation.
However I get an error stating "IllegalArgumentException: A
constructor invocation in class BadInitializer was unexpected."
as if I was supposed to configure my mock with a EasyMock-like
expectation.
* First question : Am I supposed to configure one? *
Anyway I tried to mimick Johan Haleby's file creation example (http://
blog.jayway.com/2009/10/28/untestable-code-with-mockito-and-
powermock/) with :
public void testOnlyInitializedOnce() throws Exception {
whenNew(BadInitializer.class).withNoArguments().thenCallRealMethod
();
BadInitializer.getInstance();
verifyNew(BadInitializer.class).withNoArguments();
}
But then I get java.lang.ArrayIndexOutOfBoundsException: 0
at
org.powermock.api.mockito.internal.invocationcontrol.MockitoNewInvocationControl.invoke
(MockitoNewInvocationControl.java:53)
What am I missing here? (This error actually originates some
instrumented code in the mockito API when MethodProxy.invokeSuper())
I got things working with the following code
public void testOnlyInitializedOnce() throws Exception {
BadInitializer mock = mock(BadInitializer.class);
whenNew(BadInitializer.class).withNoArguments().thenReturn(mock);
BadInitializer.getInstance();
verifyNew(BadInitializer.class).withNoArguments();
}
But that's not quite what I wan because the real constructor isn't
called and thus I never expose the bug
* Second question : How do I expose the fact that my constructor could
be called several times with powermockito *
Thanks
Johan