问题描述
我有衍生财产 lowercaseTag
。
class Hashtag {
String tag
字符串小写标记标记
静态映射= {
lowercaseTag公式:'lower(tag)'
}
}
如果我运行以下单元测试,它将在最后一行失败,因为 lowercaseTag
属性是 null
,默认情况下,所有属性都有 nullable:false
约束。
@TestFor(Hashtag)
class HashtagSpec extends Specification {
voidTest that hashtag can be null(){
when :'hashtag为空'
def p = new Hashtag(tag:null)
then:'validation should fail'
!p.validate()
在:'hashtag不为空'时
p = new Hashtag(tag:'notNullHashtag')
then:'validation should pass'
p.validate()
}
}
问题是如何在这种情况下正确编写单元测试?感谢!
正如我确信你已经发现, lowercaseTag
不能被测试,因为它依赖于数据库; Grails单元测试不使用数据库,因此公式/表达式不被评估。我认为最好的选择是修改约束,使得 lowercaseTag
可以为空。
class Hashtag {
字符串标记
字符串小写标记
静态映射= {
lowercaseTag公式:'lower(tag)'
}
静态约束= {
lowercaseTag可空:true
}
}
否则,您必须修改测试以强制 lowercaseTag
包含一些值,以便 validate()
可以工作。
p = new Hashtag(tag:'notNullHashtag',lowercaseTag:'foo')
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!
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')
这篇关于带有派生属性的域类的Grails3单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!