簡體   English   中英

Spock在Groovy中測試ResultSet

[英]Spock testing a ResultSet in Groovy

這是我到目前為止的內容:

def "If there are results then return true otherwise return false"() {
    given:
    ResultSet resultSet = Mock()

    expect:
    resultSet.next()
}

我正在嘗試在CheckActuateProjectSetServiceImpl類中測試布爾方法checkIfRowExists(int id, int foreignKey) 如果存在行,則返回true,否則返回false。

我將如何解決這個問題?

public boolean checkIfRowExists(int id, int foreignKey){
    Resultset resultSet = checkIfRowExistsResultSet(id, foreignKey)

    return false;
}

到目前為止,上述方法尚無正確的實現方式,因為在實現解決方案之前,我先嘗試編寫測試。

謝謝

如果我在您的位置,我將進行下一個TDD步驟。

  1. 從僅針對一個測試用例的測試開始:

     def "If there not are results then return false"() { given: def service = new CheckActuateProjectSetServiceImpl() expect: !service.checkIfRowExists(1, 2) } 
  2. 實現該方法以滿足測試:

     boolean checkIfRowExists(int id, int foreignKey) { return false; } 
  3. 如果有一些結果,請添加新的測試案例:

     def "If there are results then return true"() { given: def service = new CheckActuateProjectSetServiceImpl() expect: service.checkIfRowExists(1, 2) } 
  4. 現在我們被迫實施我們的方法。 該方法將執行數據庫查詢,並檢查實際結果集是否為空。 由於數據庫查詢不在單元測試范圍內,因此我們將其提取到一個單獨的方法中,稍后將在測試中覆蓋它:

     boolean checkIfRowExists(int id, int foreignKey) throws SQLException { ResultSet resultSet = getResultSet(id, foreignKey); return resultSet.next(); } ResultSet getResultSet(int id, int foreignKey) { return null; // TODO should be implemented } 
  5. 現在我們的測試由於NullPointerException而失敗,因為getResultSet()返回null 讓我們返回一個模擬的ResultSet ,它在next()調用時返回true

     def "If there are results then return true"() { given: ResultSet mockedResultSet = Mock(ResultSet) mockedResultSet.next() >> true def service = new CheckActuateProjectSetServiceImpl() { @Override def ResultSet getResultSet(int id, int foreignKey) { return mockedResultSet; } } expect: service.checkIfRowExists(1, 2) } 

    測試現在是綠色的。

  6. 第一個測試也要修復,模擬在next()調用中返回false

     def "If there not are results then return false"() { given: ResultSet mockedResultSet = Mock(ResultSet) mockedResultSet.next() >> false def service = new CheckActuateProjectSetServiceImpl() { @Override def ResultSet getResultSet(int id, int foreignKey) { return mockedResultSet; } } expect: !service.checkIfRowExists(1, 2) } 

希望它會有所幫助。 這些步驟只是以TDD風格前進的方向。 當然,您的現實情況有所不同,並且可能需要我上面提出的更具體的內容。

暫無
暫無

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

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