Grails单元测试-每个闭包的模拟findAllBy()方法

问题描述 投票:-1回答:1

我想对服务类中的功能进行单元测试。

服务类如下:

    class FooService{ 

    Double getFoo(SomeClass class){
      Double returningValue = 0.0
      String parameter

      SomeClass.findAllByCodeLike(parameter).each{
        Double amount = someOtherFooServiceMethod(it,it.someClassAttribute?.intValue())
        if(amount){
         returningValue += amount;
         }
       }
     }

    }



我知道如何模拟SomeClass.findAllByCodeLike(parameter)。我用SomeClass.metaClass.static.findAllByCodeLike()对其进行了模拟,并为该函数分配了一个值。

但是我不知道如何模拟。each {}。有办法吗?

现在,我正在模拟许多域类以测试此方法,并将域类保存到内存数据库中。如果我找到一种模拟SomeClass.findAllByCodeLike(parameter).each {...}的方法,则可以通过大量代码来减少TestClass。

unit-testing grails groovy mockito spock
1个回答
1
投票

您不必嘲笑each{}。您应该简单地使您的findAllByCodeLike模拟返回值列表:

SomeClass.metaClass.static.findAllByCodeLike = { code -> [ new SomeClass(...), new SomeClass(...), ... ] }
//...
SomeClass.findAllByCodeLike(parameter).each{ 
  doStuff it
}
© www.soinside.com 2019 - 2024. All rights reserved.