I want to unit test the return value of some code which looks similar to this:
Groovy Service code to test:
def findByThisAndThat(something) {
:
def items = []
sql.eachRow(query, criteriaList, {
def item = new Item(name:it.NAME)
items.add(item)
})
[items: items, whatever:whatevervalue]
}
Unit test code plan:
void testFindByThisAndThatReturnsAMapContainingItems(){
Sql.metaClass.eachRow = { String query, List criteria, Closure c ->
// call closure to get passed in items list
// add one new Item(name:"test item") to list
}
def result = service.findByThisAndThat("", "")
assert result.items
assertEquals('test item', result.items[0].name)
}
How can I do that?
Thanks!
Call the closure by using it like a method. Alternatively, you can use
Closure.call()as well. Pass in the value foritas the first parameter.Note that the Sql metaClass won’t get reset at the end of the test. I’d recommend clearing it out after the test: