给定grails doc的示例:

class Airport {
    …
    static hasMany = [flights: Flight]
    static mapping = {
        flights sort: 'number', order: 'desc'
    }
}

一个测试如何排序?

最佳答案

如文档中所述,它不能像书面形式那样工作。您必须将static belongsTo = [airport:Airport]添加到Flight。

如果没有belongsTo,则会出现以下错误:

单向一对多关系不支持关联的默认排序[机场->航类]。

使用belongsTo,测试可能如下所示:

class SortSpec extends IntegrationSpec {
    def "test grails does sort flights" () {
        given:
        def airport = new Airport()
        airport.addToFlights (new Flight (number: "A"))
        airport.addToFlights (new Flight (number: "C"))
        airport.addToFlights (new Flight (number: "B"))
        airport.save (failOnError: true, flush:true)

        when:
        def sortedAirport = airport.refresh() // reload from db to apply sorting

        then:
        sortedAirport.flights.collect { it.number } == ['C', 'B', 'A']
    }
}

但是..编写这样的测试并没有多大意义,因为它会检查grails是否应用了排序配置。我为什么要测试grails?测试您的代码而不是框架。

10-06 04:07