单元测试是对单元块代码的测试。换句话说你在分别测试各个方法或代码段时,不需要考虑它们外层周围代码结构。
在Grails框架中,你要特别注意单元测试和集成测试之间的一个不同点,因为在单元测试中,Grails在集成测试和测试运行时,不会注入任何被调用的动态方法。
这样做是有意义的,假如你考虑到,在Grails中各个数据库注入的各自方法(通过使用GORM),和潜在使用的Servlet引擎(通过控制器)。
例如,你在 BookController调用如下的一个服务应用:class MyService {
def otherService
String createSomething() {
def stringId = otherService.newIdentifier()
def item = new Item(code: stringId, name: "Bangle")
item.save()
return stringId
}
int countItems(String name) {
def items = Item.findAllByName(name)
return items.size()
}
}
正如你看到的,这个应用调用了GORM,那么你用在单元测试中怎样处理如上这段代码呢?
答案在Grails测试支持类中可以找到。