[英]How to test code with singletons?
我有一个旧的应用程序,其代码片段如下:
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() )而不改变类的设计(不删除单例)?
这些方面的东西:
// 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框架。
有了它,你可以模拟静态方法。 http://code.google.com/p/powermock/wiki/MockStatic
如果您的测试依赖于System.currentTimeMillis()
,这也非常有用,因为您也可以模拟它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.