Grails3 unit test for domain class with derived property

岁酱吖の 提交于 2019-12-11 12:36:55

问题


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')


来源:https://stackoverflow.com/questions/34945824/grails3-unit-test-for-domain-class-with-derived-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!