问题
Given the example from grails doc:
class Airport {
…
static hasMany = [flights: Flight]
static mapping = {
flights sort: 'number', order: 'desc'
}
}
How can one test sorting?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/24905773/grails-testing-sort-mapping-in-a-domain-class