在使用Spock的Grails中测试beforeUpdate或beforeInsert

时间:2014-04-29 15:53:03

标签: grails groovy spock beforeupdate

我是Grails的新手,我正在做一些测试但是虽然在开发中调用了beforeUpdate和beforeInsert,但我的测试表明他们不是,我做错了什么?

我正在嘲笑Cicle和Measurement所以我认为当调用方法save时,会触发beforeUpdate或beforeInsert,但是当我运行测试时,grails回答saing“调用的次数太少:1 * cicle.updateCicleValue( )(0次调用)“

我是否正确使用“何时”?或者save不会在mock对象中触发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()
}
}

谢谢!

1 个答案:

答案 0 :(得分:6)

//Integration Spec
import grails.test.spock.IntegrationSpec

class AuthorIntSpec extends IntegrationSpec {

    void "test something"() {
        given:
           def author

        when:
            Author.withNewSession {
                author = new Author(name: 'blah').save(flush: true)
            }

        then:
            author.name == 'foo'
    }
}

//Author
class Author {
    String name

    def beforeInsert() {
        this.name = 'foo'
    }
}

另请注意,如果您最终持久保存任何实体,请在事件中使用withNewSession,尽管上述简单测试会在未指定withNewSesion的情况下通过(为简洁起见)。

在您的用例中,没有涉及模拟,因此测试交互是不可能的,但您可以断言circleValue的值在插入(刷新)之后已更新,而后者又测试beforeInsert 1}}事件被适当地触发。