Groovy 元类根据调用顺序添加多个方法而不是模拟

Groovy metaclass add multiple methods based on invocation order not mock

我正在尝试覆盖 groovy sql class 上的调用方法,我能够做到 it.But 我需要根据顺序使用不同的实现。

 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.

实现它的一种方法是在 class 中使用内部标志。 然后根据标志调用不同的实现。

Sql.metaClass.first = true
Sql.metaClass.call = {String sql, List params, Closure c ->    
   if (first){
     c(mockResultSet)
     first = false
   }else{
     c(expectedLookupId)
   }
}     

感谢@Joachim suggestion.This 为我工作。

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