在grails中,如何测试具有关联的查询?

时间:2014-07-04 11:54:19

标签: unit-testing grails spock

我想要测试where query,但它总是返回一个空列表。如果我删除owner.name == "Jane"查询返回的内容,但是当我把它放回去时,它不再返回任何内容。 where查询肯定适用于test-app上的基本模型搜索,但是,我不确定它是否在包含关联时有效。它在run-app上运行正常,但它似乎在test-app上失败了。难道我做错了什么?我需要嘲笑某事吗?我正在使用grails 2.3.9和spock。注意:我正在进行单元测试。

 Owner owner = Owner.build(name: "Jane")
 Pet expectedPet = Pet.build(breed: "Random dog", owner:owner)

 when:
 def pets = Pet.where {
            breed == "Random dog" && owner.name == "Jane"
 }.list()

 then:
 pets.size() == 1

1 个答案:

答案 0 :(得分:2)

但是,我可以通过自己的域名通过测试。我的假设是您的域中可能有其他字段导致save失败。我的建议是使用buildWithoutSave并使用failOnError:true自行保存以进一步调试。

希望有所帮助

//规范:

import grails.buildtestdata.mixin.Build
import spock.lang.Specification

@Build([Owner, Pet])
class OwnerSpec extends Specification {

    def setup() {
    }

    def cleanup() {
    }

    void "test something"() {
        setup:

        //Owner owner = Owner.build(name: "Jane")
        //Pet expectedPet = Pet.build(breed: "Random dog", owner: owner)

       Owner owner = Owner.buildWithoutSave(name: "Jane")
       owner.save(failOnError: true)

       Pet expectedPet = Pet.buildWithoutSave(breed: "Random dog", owner: owner)           
       expectedPet.save(failOnError: true)

        when:
        def pets = Pet.where {
            breed == "Random dog" && owner.name == "Jane"
        }.list()

        then:
        pets.size() == 1
    }
}

//域

class Pet {

    String breed
    testsave.Owner owner

    static constraints = {
    }
}

class Owner {
    String name

    static constraints = {
    }
}