Friday 7 December 2018

java - Mocking static methods with Mockito



I've written a factory to produce java.sql.Connection objects:




public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory {

@Override public Connection getConnection() {
try {
return DriverManager.getConnection(...);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}



I'd like to validate the parameters passed to DriverManager.getConnection, but I don't know how to mock a static method. I'm using JUnit 4 and Mockito for my test cases. Is there a good way to mock/verify this specific use-case?


Answer



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:





No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...