我有一个带有以下代码片段的旧应用程序:

public class MyClass
{
    public void executeSomeSqlStatement()
    {
        final Connection dbConn = ConnectionPool.getInstance().getConnection();

        final PreparedStatement statement = dbConn.prepareStatement(); // NullPointerException, if ConnectionPool.getInstance().getConnection() returns null
    }
}

我想编写一个单元测试,以验证当ConnectionPool.getInstance()。getConnection()返回null时,MyClass.executeSomeSqlStatement不会引发NullPointerException。

我该如何做(模拟ConnectionPool.getInstance()。getConnection()),而无需更改类的设计(不删除单例)?

最佳答案

您可以使用PowerMock,它支持模拟静态方法。

遵循以下原则:

// 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

09-18 17:45