-->

Grails3 unit test for domain class with derived pr

2019-08-06 04:39发布

问题:

I have the following Domain class with derived property lowercaseTag.

class Hashtag {
    String tag
    String lowercaseTag

    static mapping = {
        lowercaseTag formula: 'lower(tag)'
    }
}

If I run the following unit test, it will fail on the last line, because lowercaseTag property is null and by default all properties have nullable: false constraint.

@TestFor(Hashtag)
class HashtagSpec extends Specification {
    void "Test that hashtag can not be null"() {
        when: 'the hashtag is null'
        def p = new Hashtag(tag: null)

        then: 'validation should fail'
        !p.validate()

        when: 'the hashtag is not null'
        p = new Hashtag(tag: 'notNullHashtag')

        then: 'validation should pass'
        p.validate()
    }
}

The question is how to properly write unit tests in such cases? Thanks!

回答1:

As I'm sure you've figured out, the lowercaseTag cannot be tested because it's database dependent; Grails unit tests do not use a database, so the formula/expression is not evaluated.

I think the best option is to modify the constraints so that lowercaseTag is nullable.

class Hashtag {
    String tag
    String lowercaseTag

    static mapping = {
        lowercaseTag formula: 'lower(tag)'
    }

    static constraints = {
        lowercaseTag nullable: true
    }
}

Otherwise, you'll have to modify the test to force lowercaseTag to contain some value so that validate() works.

p = new Hashtag(tag: 'notNullHashtag', lowercaseTag: 'foo')