How to break a closure to check the result of a Grails service?

I want unit test to return the value of some code that looks something like 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:

   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 this? Thank!

+3
source share
2 answers

Call a closure using it as a method. Alternatively, you can use Closure.call(). Pass the value as the first parameter it.

Sql.metaClass.eachRow = { String query, List criteria, Closure c ->
    def mockItems = ["test item"]
    mockItems.each { item ->
        c(item)
        // c.call(item) works too
    }
}

Note that at the end of the Sql test, metaClass will not receive a reset. I recommend cleaning it after the test:

Sql.metaClass = null
+1
source

A unit test, , , . , db.

, , .

+2

Source: https://habr.com/ru/post/1786553/


All Articles