I have a validator inside a domain class and I have a problem testing the controller for Lagerort.
com.example.xyz.LagerortControllerSpec > Test the update action performs an update on a valid domain instance FAILED
java.lang.IllegalStateException: Either class [com.example.xyz.Lagertyp] is not a domain class or GORM has not been initialized correctly or has already been shutdown. Ensure GORM is loaded and configured correctly before calling any methods on a GORM entity.
If I omit the validator, everything tests fine, but that's not what I want.
The domain class:
class Lagerort {
String lagerort
Lagertyp lagertyp
String beschreibung
static auditable = true
static constraints = {
lagerort(nullable: false, blank: false, unique: true)
lagertyp(nullable: false, blank: false, validator: { val, obj ->
// Only ONE Lagerort may be "Schrott"
if (Lagertyp.count() > 0) {
def _LAGERTYPSTRING="Schrott"
Lagertyp lagertypschrott = Lagertyp.findByLagertyp(_LAGERTYPSTRING)
if (obj.lagertyp == lagertypschrott && Lagerort.countByLagertyp(lagertypschrott)>0) return ['lagerortschrottunique',_LAGERTYPSTRING]
}
})
beschreibung(nullable: false, blank: false)
}
String toString(){lagerort}
}
The testCompile part of the dependencies in build.gradle looks like this:
testCompile "org.grails:grails-plugin-testing"
testCompile "org.grails.plugins:geb"
testCompile "org.grails.plugins:hibernate5"
testRuntime "org.seleniumhq.selenium:selenium-htmlunit-driver:2.47.1"
testRuntime "net.sourceforge.htmlunit:htmlunit:2.18"
I've already tried creating a few objects of type Lagertyp in the setup part of the controller tests so that Lagertyp.count() > 0
would be true for the validator, but that didn't help either.
The populateValidParams of the LagerortControllerSpec / test looks like this:
def populateValidParams(params) {
assert params != null
params["lagerort"] = 'Fa.Conrad'
params["lagertyp"] = ["lagertyp": 'Fa.Conrad', "beschreibung": 'Motor befindet sich bei Fa.Conrad']
params["beschreibung"] = 'in Reparatur bei Fa. Conrad'
}
The LagerortController: https://pastebin.com/PpZ5zqMm
The test for LagerortController: https://pastebin.com/pxZ6UeVK
Any ideas?
Found the solution, I had to also mock Lagertyp, like so:
@Mock([Lagerort,Lagertyp])
It seems that I have to include all domain classes which are part of the tests inside the @Mock
list, even those that are referenced indirectly.