grails: testing 'sort' mapping in a domain class

青春壹個敷衍的年華 提交于 2019-12-12 01:59:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!