I\'ve written a factory to produce java.sql.Connection
objects:
public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory
For those who use JUnit 5, Powermock is not an option. You'll require the following dependencies to successfully mock a static method with just Mockito.
testCompile group: 'org.mockito', name: 'mockito-core', version: '3.6.0'
testCompile group: 'org.mockito', name: 'mockito-junit-jupiter', version: '3.6.0'
testCompile group: 'org.mockito', name: 'mockito-inline', version: '3.6.0'
mockito-junit-jupiter
add supports for JUnit 5.
And support for mocking static methods is provided by mockito-inline
dependency.
Example:
@Test
void returnUtilTest() {
assertEquals("foo", UtilClass.staticMethod("foo"));
try (MockedStatic classMock = mockStatic(UtilClass.class)) {
classMock.when(() -> UtilClass.staticMethod("foo")).thenReturn("bar");
assertEquals("bar", UtilClass.staticMethod("foo"));
}
assertEquals("foo", UtilClass.staticMethod("foo"));
}
The try-catch block is used to make the static mock remains temporary, so it's mocked only within that scope. But It's not mandatory to use a try-catch block.