Search code examples
javaintellij-ideagrails

Grails: Can't access set of hasMany Relation (No such property)


I'm currently working on the unit tests for the domain classes I've built. But for some reason I can't access the elements in the 'hasMany' realation.

When I try to access the property 'module.exams' it throws an exception groovy.lang.MissingPropertyException: No such property: exams for class: ch.fhnw.webec.Module.

I've seen countless examples where people access the property. I tried exams, getExams, addTo etc. but none works.

void 'test module relation'() {

    Teacher teacher = new Teacher(prename: "Max", surname: "Mustermann")
    Module module = new Module(name: "Workshop 1", shortName: "WS2", credits: 3, year: 2019, isSpring: true, teacher: teacher)

    Exam exam1 = new Exam(module: module, name: "Prüefung 01", isMsp: false, number: 1, weight: 1, date: Date.parse("yyyy-MM-dd", "2019-03-28"))
    Exam exam2 = new Exam(module: module, name: "Prüefung 01", isMsp: false, number: 1, weight: 1, date: Date.parse("yyyy-MM-dd", "2019-03-28"))

    expect:
    module.exams.count() == 2 // <--  this line
}



package ch.fhnw.webec

class Module {
// ....
    static hasMany = [exams: Exam]
// ...
}

Solution

  • Through try an error and tons of question on the internet I found a solution. Instead of deleting the question I thought I'd explain the solution. Maybe this can help others that try to figure this out as well:

    Thanks to JeffScottBrown for pointing that out: By default it creates a set. Which means addToXXX does work. But for in my case I needed a list and this is what I had to add:

     class Module {
        static hasMany = [exams: Exam]
        List exams
        // ...
    }
    

    But adding those isn't enough. When creating the objects you have to add them to this list via the generated 'addToXY' method:

        module.addToExams(exam1)
        module.addToExams(exam2)
    
        assert module.exams.size() == 2