I have an old application with code fragments like these:
public class MyClass
{
public void executeSomeSqlStatement()
{
final Connection dbConn = ConnectionPool.getInstance().getConnection();
final PreparedStatement statement = dbConn.prepareStatement(); // NullPointerException, if ConnectionPool.getInstance().getConnection() returns null
}
}
I want to write a unit test, which verifies that MyClass.executeSomeSqlStatement doesn't throw a NullPointerException, when ConnectionPool.getInstance().getConnection() returns null.
How can I do it (mock ConnectionPool.getInstance().getConnection()) without changing the design of the class (without removing the singleton) ?
You can use PowerMock, which supports mocking of static methods.
Something along these lines:
// at the class level
@RunWith(PowerMockRunner.class)
@PrepareForTest(ConnectionPool.class)
// at the beginning your test method
mockStatic(ConnectionPool.class);
final ConnectionPool cp = createMock(ConnectionPool.class);
expect(cp.getConnection()).andReturn(null);
expect(ConnectionPool.getInstance()).andReturn(cp);
replay(ConnectionPool.class, cp);
// the rest of your test
I recommend to use the PowerMock framework.
With it you can mock static methods. http://code.google.com/p/powermock/wiki/MockStatic
This can also be very useful if your tests depend on System.currentTimeMillis(), because you can mock it too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With