3

我有一个旧应用程序,其中包含如下代码片段:

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())而不改变类的设计(不删除单例)?

4

2 回答 2

5

您可以使用支持模拟静态方法的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
于 2013-09-20T07:03:21.303 回答
4

我推荐使用 PowerMock 框架。

有了它,您可以模拟静态方法。http://code.google.com/p/powermock/wiki/MockStatic

如果您的测试依赖于 ,这也非常有用System.currentTimeMillis(),因为您也可以模拟它。

于 2013-09-20T07:03:41.857 回答