【问题标题】:Grails domain validate keeps returning false positives for unit testGrails 域验证不断返回单元测试的误报
【发布时间】:2014-08-04 17:44:58
【问题描述】:

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

发生了什么:在对服务进行单元测试期间,尽管子域未满足约束条件,但 validate 始终返回 true。 请帮忙...

【问题讨论】:

    标签: grails groovy grails-orm


    【解决方案1】:

    我对我的代码有两处更改: 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 }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 2011-09-14
      相关资源
      最近更新 更多