4
votes

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()
    }
}
1
set the validate:true see if you are lacking any constraints - Alidad
How does Term look like? - dmahapatro
@Alidad I am lacking several constraints for sure, but I thought that setting validate: false would mean that validation wouldn't trigger on a save so I don't have to fill out all fields. @dmahapatro I added Term to the original post. - grantmcconnaughey
Why Integer id? GORM default is Long id and do not need to specify it explicitly. - dmahapatro
Is the id generator assigned? Can you try t.id = 1 and then t.save(...) in the test, without setting id as the map construct. - dmahapatro

1 Answers

8
votes

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(...)