Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test code with singletons?

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

like image 268
Dmitrii Pisarenko Avatar asked Jun 15 '26 11:06

Dmitrii Pisarenko


2 Answers

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
like image 91
Adam Siemion Avatar answered Jun 17 '26 01:06

Adam Siemion


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.

like image 40
René Link Avatar answered Jun 17 '26 01:06

René Link