3

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) ?

Glory to Russia
  • 17,289
  • 56
  • 182
  • 325

2 Answers2

5

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
Adam Siemion
  • 15,569
  • 7
  • 58
  • 92
4

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.

René Link
  • 48,224
  • 13
  • 108
  • 140