Grails域验证不断返回单元测试的误报

时间:2014-08-04 17:44:59

标签: grails groovy gorm

我想要的:当我在单元测试期间调用父域上的验证(或保存)时,它将检查所有子域及其子项及其子项等的约束。

正在发生的事情:在服务的单元测试期间,尽管子域未满足约束,但validate仍会返回true。 请帮忙......

1 个答案:

答案 0 :(得分:0)

我有两个关于我的代码的改变: 1)我必须确保所有域都被模拟为单元测试。 2)我必须确保填充了每个子域的对父项的后向引用。 obj.addToSomeProperty(property)自动填充一对多对象的引用,但是对于一对一,我必须手动设置它。

服务单位测试:

@TestFor(GardenerService)
@Mock([Orchard, Plot, Tree, Fruit])
class GardenerServiceSpec extends Specification {
    void "test save and fetch"() {
        setup:
        Fruit fruit = new Fruit(name:"Peach")
        Tree tree = new Tree(height:6)
        tree.addToFruits(fruit)
        Plot plot = new Plot(litersOfWaterAdded:10)

        plot.tree = tree  // Must be a better way... why didn't setTree(tree) 
        tree.plot = plot  //   set the back reference

        Orchard orchard = new Orchard(orchardName:"Eden")
        orchard.addToPlots(plot)

        when:
        orchard.save(flush: true)

        then:
        orchard.validate()
        Fruit.findByName("Peach").tree.plot.orchard.name == "Eden"
        Tree.findByHeight(6).plot.litersOfWaterAdded == 10
    }
}

域:

class Orchard {
    String orchardName
    static hasMany = [plots: Plot]
}

class Plot{
    static belongsTo = [orchard: Orchard]
    int litersOfWaterAdded
    static hasOne = [tree: Tree]
}

class Tree {
    static belongsTo = [plot: Plot]
    int height
    static hasMany = [fruits: Fruit]
}

class Fruit {
    static belongsTo = [tree: Tree]
    String name
    String description

    static constraints = { description nullable: true }
}