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?
I had a similar issue. The accepted answer did not work for me, until I made the change:
@PrepareForTest(TheClassThatContainsStaticMethod.class)
, according to PowerMock's documentation for mockStatic.And I don't have to use
BDDMockito
.My class:
My test class:
Mockito cannot capture static methods, but since Mockito 2.14.0 you can simulate it by creating invocation instances of static methods.
Example (extracted from their tests):
Their goal is not to directly support static mocking, but to improve its public APIs so that other libraries, like Powermockito, don't have to rely on internal APIs or directly have to duplicate some Mockito code. (source)
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.
Use JMockit framework. It worked for me. You don't have to write statements for mocking DBConenction.getConnection() method. Just the below code is enough.
@Mock below is mockit.Mock package