Spock Web Console

subscribe to the feed Subscribe
Let's stub a ResultSet! (via #spockwebconsole)
tweet this script Tweet

Let's stub a ResultSet!

Published 2 years ago by Peter Niederwieser with tags #mocking
Actions  ➤ Edit In Console Back To Console Show/Hide Line Numbers View Recent Scripts
import java.sql.ResultSet
import java.sql.Date

@See("http://canoo.com/blog/2010/11/05/advanced-mocking-capturing-state-with-answer-and-captors/")
class LetsStubAResultSet extends Specification {
  def "let's do it!"() {
    def resultSet = makeResultSet(
      ["Id", "Name"  , "Birthday"    ],
      [  1 , "Hamlet", new Date(9999)],
      [  2 , "Andres", new Date(8888)],
      [  3 , "Dierk" , new Date(7777)]
    )

    expect:
    resultSet.next()
    resultSet.getInt("Id") == 1

    resultSet.next()
    resultSet.getString("Name") == "Andres"

    resultSet.next()
    resultSet.getDate("Birthday") == new Date(7777)

    !resultSet.next()
  }
  
  private ResultSet makeResultSet(List<String> aColumns, List... rows) {
    ResultSet result = Mock()
    int currentIndex = -1   
  
    result.next() >> { ++currentIndex < rows.length } 
    result./get(String|Short|Date|Int|Timestamp)/(_) >> { String argument ->
      rows[currentIndex][aColumns.indexOf(argument)]   
    }     

    return result
  }  
}