gra*_*hey 4 testing grails junit unit-testing
我想成为一个优秀的小程序员并为我的Grails 2.2.3应用程序设置单元测试.使用GORM注入.save()方法的单元测试显然不会持久存在于模拟测试数据库中.例如,以下是一个测试包含的内容:
@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
}
}
Run Code Online (Sandbox Code Playgroud)
我做了一个println最终打印Printing Term: null,这意味着Term没有保存并返回Term实例.Term.count()返回0时,第一个断言为false .
有谁知道为什么会这样?我有一个模拟Term和TermService(我相信通过TestFor注释),所以我不太清楚为什么这不起作用.谢谢!
编辑:这是我的Term课程.
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()
}
}
Run Code Online (Sandbox Code Playgroud)
看起来像id生成器,assigned因为您已经提到过使用旧数据库.id在域类中默认情况下,Plus 不可绑定(map构造不适用于id).所以,我认为你必须最终使用如下:
def t = new Term(code: "201310")
t.id = 1
t.save(...)
Run Code Online (Sandbox Code Playgroud)