grails: testing 'sort' mapping in a domain

2019-08-31 16:37发布

Given the example from grails doc:

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

How can one test sorting?

2条回答
SAY GOODBYE
2楼-- · 2019-08-31 16:47

For sorting in case of association, simply do the following:

class UserProjectInvolvement {
Project project

 static mapping = {
    sort 'project.name'
 }
}

I am using 2.4.4 and it is working perfectly.

查看更多
虎瘦雄心在
3楼-- · 2019-08-31 17:00

As stated in the docs, it does not work like written. You have to add static belongsTo = [airport:Airport] to Flight.

Without belongsTo you get the following error:

Default sort for associations [Airport->flights] are not supported with unidirectional one to many relationships.

With belongsTo the test could look like this:

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']
    }
}

But.. it doesn't make much sense to write a test like this because it checks that grails applies the sorting configuration. Why would I want to test grails? Test your code and not the framework.

查看更多
登录 后发表回答