简体   繁体   中英

How to mock static closures in Groovy/Grails

I'm trying to unit ( not integration) test a piece of legacy code that I can't change:

class Job {
 public boolean isStale(String param) {
     def status
     StatusObj.withTransaction {
        status = StatusObj.findByJobIdAndParam(getId(), param)
     }
     return status
 }
}

and here is my attempt to Stub it:

 def  () {
        setup:        
        GroovySpy(StatusObj, global: true)       
        StatusObj.withTransaction(_) >> StatusObj
        StatusObj.findByJobIdAndParam(_,_) >> 2


        when:
        def isStale = job.isStale("test")
        then:
        isStale == 2
    }

I can't figure out how to get to the inner mock

Try something like this:

@Unroll
class JobSpec extends Specification {
    def "spec"() {
        when:
        GroovySpy(StatusObj, global: true)
        def job = new Job(id: "ID")
        def param = "test"
        1 * StatusObj.withTransaction(_) >> { Closure action ->
            action.call()
        }
        1 * StatusObj.findByJobIdAndParam(job.id, param) >> status

        then:
        job.isStale(param) == isStale

        where:
        status | isStale
        0      | false
        1      | true
        2      | true
    }
}

Here action is your status = StatusObj.findByJobIdAndParam(getId(), param) from Job class. How it works can be found in sections Computing Return Values and Performing Side Effects of Spock documentation. Also, note that I've made Job.getId() work by adding id field to Job class. I'm not sure how it's implemented in your code

The findByJobIdAndParam takes 2 args:

status = StatusObj.findByJobIdAndParam(getId(), param)

Your stub takes 1 arg:

StatusObj.findByJobIdAndParam(_) >> 2

Try changing the stub like that:

StatusObj.findByJobIdAndParam(_, _) >> 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM