Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails unit tests not recognizing .save() on a domain class

I am trying to be a good little programmer and set up Unit tests for my Grails 2.2.3 app. The unit tests that use GORM's injected .save() method are apparently not persisting to the mock test DB. For an example, here is what one test consists of:

@TestFor(TermService)
@Mock(Term)
class TermServiceTests {
    void testTermCount() {
        def t = new Term(code: "201310").save(validate: false, flush: true, failOnError: true)
        println "Printing Term: " + t.toString()

        assert 1 == Term.count() // FAILS
        assert service.isMainTerm(t) // FAILS
    }
}

I did a println that ends up printing Printing Term: null, meaning the Term did not save and return a Term instance. The first assertion is false with Term.count() returning 0.

Does anyone know why this might be? I have a mock Term and TermService (via the TestFor annotation, I believe), so I'm not quite sure why this wouldn't work. Thanks!

Edit: Here is my Term class.

class Term {

    Integer id
    String code
    String description
    Date startDate
    Date endDate

    static mapping = {
        // Legacy database mapping
    }

    static constraints = {
        id blank: false
        code maxSize: 6
        description maxSize: 30
        startDate()
        endDate()
    }
}
like image 415
grantmcconnaughey Avatar asked Feb 16 '23 16:02

grantmcconnaughey


1 Answers

Looks like id generator is assigned since you have mentioned about using legacy database. Plus id is not bindable by default in domain class (map construct won't work for id). So, I think you have to end up using like below:

def t = new Term(code: "201310")
t.id = 1
t.save(...)
like image 59
dmahapatro Avatar answered Feb 24 '23 05:02

dmahapatro