1

我是 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()
}
}

谢谢!

4

1 回答 1

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事件是否被适当地触发。

于 2014-05-01T04:58:02.197 回答