【问题标题】:How to test code with singletons?如何用单例测试代码?
【发布时间】:2013-09-20 07:00:53
【问题描述】:

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

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

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

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

如何在不改变类设计(不删除单例)的情况下(模拟 ConnectionPool.getInstance().getConnection())做到这一点?

【问题讨论】:

标签: java unit-testing mocking


【解决方案1】:

您可以使用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

【讨论】:

  • 我应该使用哪个版本的 PowerMock?在 1.5.1 中没有 PowerMock.expect 方法。
  • @DmitriPisarenko 它们由选择与 PowerMock 一起使用的模拟库提供:EasyMock 或 Mockito。
【解决方案2】:

我推荐使用 PowerMock 框架。

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

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

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    相关资源
    最近更新 更多