Question

I want to write a unit test (by JUnit) to test value of this function in Groovy:

    String getPeopleNamesById(int[] peopleIds) {
        List<String> names = People.createCriteria().list{
            projections { property("name") }
            'in' ("id", peopleIds)
        }
        return names ? names.join(", ") : "";
    }

But the unit test always fails when reading this statement: List names = People.createCriteria().list{...} groovy.lang.MissingMethodException: No signature of method: People.createCriteria() is applicable for argument types: () values: []. I guess it because of calling to functions which execute some DB connections and queries? Could you please help me write this test? Thank you so much!

Was it helpful?

Solution

Criteria queries aren't available in unit tests, and aren't provided by mockDomain. You can either mock your criteria queries yourself, e.g. with mockFor, or make your test an integration test, where you have access to a full database environment.

Here's an example of how you could mock your query:

mockFor(People).demand.static.createCriteria = { ->
    [list: { closure -> [ <some mock objects> ] } ]
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top