Raibaz
Raibaz

Reputation: 9710

Testing criteria creation in a Grails service

I have a Grails service that creates a criteria query with optional parameters like this:

List<Car> search(String make = "%", String model = "%", Integer year = null) {
    def c = Car.createCriteria()

    return c.list() {
        if(make) {
            like("make", make)
        }
        if(model) {
            like("model", model)
        }
        if(year) {
            eq("year", year)
        }
    }
}

(Also, is this the idiomatic way to do this in grails? I'm quite new to the framework and I'm trying to find the right way to do things)

I'd like to test that the proper criteria filters are set according to the values of the parameters of the search method but I'm having no success.

I tried some variations of this:

@TestFor(CarService)
@Mock(Car)
class CarServiceSpec extends Specification {
    def car = Mock(Car)
    void "empty filters"() {
        when: service.search()
        then:
        with(car.createCriteria()) {
            0 * like(*_)
            0 * eq(*_)
        }
    }
}

But I can't seem to find a way to do assertions about the interactions between the CarService and the criteria object.

What am I missing?

Upvotes: 0

Views: 182

Answers (1)

Joe
Joe

Reputation: 1219

The Grails Where query instead of the Criteria query seems to be better choice for an idiomatic way to do this in Grails:

Gorm Where Query

Upvotes: 1

Related Questions