Hi everyone,
I hope I'm posting this to the right mailing list (despite the error message below).
I have difficulties setting a private static field in a class for one of my tests. Here is the class under test; the test is just below it.
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
//...
public class MyService extends ServiceUtils {
private static PoolingClientConnectionManager connectionManager;
private static DefaultHttpClient httpClient;
private ServiceLog log;
//...
public void doDestroy() throws ServiceException {
log.logDebug("Shutting down Connection Manager...");
try {
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
// catch any exception, format it, and pass it up.
throw new ServiceException(ErrorWrapper.formatException(e), e);
}
log.logInformation("Done.");
}
}
Now I want to test if the shutdown() method is actually called:
public class MyServiceTest {
@Test
public final void test_doDestroy() throws ServiceException {
// variables
PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
PoolingClientConnectionManager spyConnectionManager = spy(connectionManager);
DefaultHttpClient httpClient = new DefaultHttpClient(spyConnectionManager);
MyService myService = new MyService();
// start setup mocks
ServiceLog mockedLog = mock(ServiceLog.class);
// end setup mocks
// start setup behaviour
Whitebox.setInternalState(myService, "log", mockedLog);
Whitebox.setInternalState(MyService.class, "httpClient", httpClient);
// end setup behaviour
// act
stuboService.doDestroy();
// verify
verify(spyConnectionManager, times(1)).shutdown();
verify(mockedLog, times(1)).logDebug(anyString());
verify(mockedLog, times(1)).logInformation(anyString());
}
}
The above returns "java.lang.RuntimeException: Unable to set internal state on a private field. Please report to mockito mailing list." for the bold line.
If I change the first line to
@RunWith(PowerMockRunner.class)
@PrepareForTest({MyService.class})
public class MyServiceTest
I get the following "org.apache.http.conn.ssl.SSLInitializationException: class configured for SSLContext: com.sun.net.ssl.internal.ssl.SSLContextImpl not a SSLContext" (not sure what that means).
But if I remove those two lines again and then go on and change the bold line to the following:
Whitebox.setInternalState(myService, "httpClient", httpClient);
the test passes - which is great, but I don't quite understand why.
I thought I had to use Whitebox.setInternalState() to set a private field, that passing in "xyz.class" would allow me to set a private static field and that I would not need to add the @RunWith and @PrepareForTest annotations if I just wanted to use PowerMock's Whitebox (and otherwise rely on Mockito). Can anyone help me, please?
Kind regards,
Christian