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?
Use PowerMockito on top of Mockito.
Example code:
More information:
I also wrote a combination of Mockito and AspectJ: https://github.com/iirekm/varia/tree/develop/ajmock
Your example becomes:
You can do it with a little bit of refactoring:
Then you can extend your class
MySQLDatabaseConnectionFactory
to return a mocked connection, do assertions on the parameters, etc.The extended class can reside within the test case, if it's located in the same package (which I encourage you to do)
The typical strategy for dodging static methods that you have no way of avoiding using, is by creating wrapped objects and using the wrapper objects instead.
The wrapper objects become facades to the real static classes, and you do not test those.
A wrapper object could be something like
Finally, your class under test can use this singleton object by, for example, having a default constructor for real life use:
And here you have a class that can easily be tested, because you do not directly use a class with static methods.
If you are using CDI and can make use of the @Inject annotation then it is even easier. Just make your Wrapper bean @ApplicationScoped, get that thing injected as a collaborator (you do not even need messy constructors for testing), and go on with the mocking.
Observation : When you call static method within a static entity, you need to change the class in @PrepareForTest.
For e.g. :
For the above code if you need to mock MessageDigest class, use
While if you have something like below :
then, you'd need to prepare the class this code resides in.
And then mock the method :
To mock static method you should use a Powermock look at: https://github.com/powermock/powermock/wiki/MockStatic. Mockito doesn't provide this functionality.
You can read nice a article about mockito: http://refcardz.dzone.com/refcardz/mockito