我是 Grails 的新手,我正在做一些测试,但是虽然在开发中调用了 beforeUpdate 和 beforeInsert,但我的测试说它们不是,我做错了什么?
我在嘲笑 Cicle 和 Measurement 所以我认为当调用方法 save 时,会触发 beforeUpdate 或 beforeInsert,但是当我运行测试时 grails 回答说“调用太少:1 * cicle.updateCicleValue() (0调用)”
那么我是否错误地使用了“何时”?还是 save 不会在模拟对象中触发 beforeUpdate 和 beforeInsert?
请帮忙 :)
Cicle.goovy
class Cicle {
String machine
double cicleValue
static hasMany = [measurements:Measurement]
def beforeInsert(){
if (measurements != null) updateCicleValue()
}
def beforeUpdate(){
if (measurements != null) updateCicleValue()
}
public void updateCicleValue(){
double sumCicleValue = 0
measurements.each{ measurement ->
sumCicleValue += measurement.cicleValue
}
cicleValue = sumCicleValue / measurements.size()
}
}
CicleSepc.groovy
@TestFor(Cicle)
@Mock([Cicle, Measurement])
class CicleSpec extends Specification {
Measurement mea1
Measurement mea2
Cicle cicle
def setup() {
mea1 = new Measurement(machine: "2-12", cicleValue: 34600)
mea2 = new Measurement(machine: "2-12", cicleValue: 17280)
cicle = new Cicle(machine: "2-12")
cicle.addToMeasurements(mea1)
cicle.addToMeasurements(mea2)
}
def cleanup() {
}
void "Test updateCicleValue is triggered"(){
when: "Saving..."
cicle.save(flush:true)
then: "updateCicleValue is called once"
1 * cicle.updateCicleValue()
}
}
谢谢!