I\'ve written a factory to produce java.sql.Connection
objects:
public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory
Use PowerMockito on top of Mockito.
Example code:
@RunWith(PowerMockRunner.class)
@PrepareForTest(DriverManager.class)
public class Mocker {
@Test
public void shouldVerifyParameters() throws Exception {
//given
PowerMockito.mockStatic(DriverManager.class);
BDDMockito.given(DriverManager.getConnection(...)).willReturn(...);
//when
sut.execute(); // System Under Test (sut)
//then
PowerMockito.verifyStatic();
DriverManager.getConnection(...);
}
More information:
Observation : When you call static method within a static entity, you need to change the class in @PrepareForTest.
For e.g. :
securityAlgo = MessageDigest.getInstance(SECURITY_ALGORITHM);
For the above code if you need to mock MessageDigest class, use
@PrepareForTest(MessageDigest.class)
While if you have something like below :
public class CustomObjectRule {
object = DatatypeConverter.printHexBinary(MessageDigest.getInstance(SECURITY_ALGORITHM)
.digest(message.getBytes(ENCODING)));
}
then, you'd need to prepare the class this code resides in.
@PrepareForTest(CustomObjectRule.class)
And then mock the method :
PowerMockito.mockStatic(MessageDigest.class);
PowerMockito.when(MessageDigest.getInstance(Mockito.anyString()))
.thenThrow(new RuntimeException());
As mentioned before you can not mock static methods with mockito.
If changing your testing framework is not an option you can do the following:
Create an interface for DriverManager, mock this interface, inject it via some kind of dependency injection and verify on that mock.