簡體   English   中英

如何用單例測試代碼?

[英]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() )而不改變類的設計(不刪除單例)?

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

有了它,你可以模擬靜態方法。 http://code.google.com/p/powermock/wiki/MockStatic

如果您的測試依賴於System.currentTimeMillis() ,這也非常有用,因為您也可以模擬它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM