0

I am trying to overwrite method Call on the groovy sql class and i am able to do it.But i need to have different implementations based on order.

 Sql.metaClass.call = {String sql, List params, Closure c -> c(mockResultSet)}      //first time should call this method
 Sql.metaClass.call = {String sql, List params, Closure c -> c(expectedLookupId)}   //second time should call this method.
mohanaki
  • 260
  • 2
  • 6
  • 15
  • possible duplicate of [mock out return of a method base on the number of invocation only in spock](http://stackoverflow.com/questions/26737268/mock-out-return-of-a-method-base-on-the-number-of-invocation-only-in-spock) – dmahapatro May 13 '15 at 15:56

2 Answers2

0

One way to implement it would be using an internal flag in the class. Then call the different implementations based on the flag.

Sql.metaClass.first = true
Sql.metaClass.call = {String sql, List params, Closure c ->    
   if (first){
     c(mockResultSet)
     first = false
   }else{
     c(expectedLookupId)
   }
}     
Jocce Nilsson
  • 1,658
  • 14
  • 28
  • What if i want to have these calls. Sql.metaClass.call = { String sql, List params, Closure c ->c(mockResultSet) // first time} Sql.metaClass.call = { String sql, List params -> params } //second time – mohanaki May 13 '15 at 18:29
0

Thanks @Joachim for the suggestion.This worked for me.

    def counter = 1
    Sql.metaClass.call = {String sql, List params, Closure c ->
        if(counter ==1 ) {
            c(mockResultSet)
            counter++;
        }else{
            c(expectedLookupId)
        }
    }
mohanaki
  • 260
  • 2
  • 6
  • 15