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

Ana*_*nco 1 grails groovy beforeupdate spock

我是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()
}   
}
Run Code Online (Sandbox Code Playgroud)

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()
}
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

dma*_*tro 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'
    }
}
Run Code Online (Sandbox Code Playgroud)

另请注意,要withNewSession在事件中使用,如果您最终持久化任何实体,尽管上述简单测试将通过而未指定withNewSesion(为简洁起见).

在您的用例中,没有涉及到模拟,因此无法对交互进行测试,但您可以断言circleValue插入(flush)之后的值已更新,这反过来会测试该beforeInsert事件是否被适当地触发.