2007-06-01
Grails中的Controller单元测试
对于Controller的单元测试,Grails也提供了很方便的支持,使得书写非常简单,有代码为证:
单元测试代码
- class CategoryControllerTests extends GroovyTestCase {
- void setUp(){
- def test1= new Category(name: "Test1", parent: null).save()
- def test2= new Category(name: "Test2", parent: null).save()
- def test3= new Category(name: "Test3", parent: null).save()
- def test11= new Category(name: "Test11", parent: test1).save()
- def test12= new Category(name: "Test12", parent: test1).save()
- def test21= new Category(name: "Test21", parent: test2).save()
- }
- void testListRoot() {
- def controller= new CategoryController()
- //categoryList对应返回的model
- def categoryList= controller.list()?.categoryList
- assertEquals 3, categoryList.size()
- assertEquals 'Test1', categoryList[0].name
- assertEquals 'Test2', categoryList[1].name
- assertEquals 'Test3', categoryList[2].name
- }
- void testListTest1(){
- def controller= new CategoryController()
- //其中的params表示的是requestparameter,后面的id是传入的参数。
- //对于session之类以此类推。
- controller.params.id= 1
- def categoryList= controller.list()?.categoryList
- assertEquals 2, categoryList.size()
- assertEquals 'Test11', categoryList[0].name
- assertEquals 'Test12', categoryList[1].name
- }
- }
Controller部分代码
- class CategoryController {
- def index = { redirect(action:list,params:params) }
- def allowedMethods = [save:'POST']
- def list = {
- if(!params.id){
- return [ categoryList: Category.findAllByParentIsNull() ]
- }else{
- def category= Category.get(params.id)
- if(category){
- return [ categoryList: Category.findAll("from Category c where c.parent.id=$params.id"), path: category.getPath()]
- }else{
- flash.message = "Category not found with id ${params.id}"
- redirect(action:list)
- }
- }
- }
- ......
- }
以上的代码基本上向开发者隐藏了背后的Mock机制,使用起来也更加简单方便。对于如此简单就能完成Controller的测试,我们没有理由不把TDD进行到底。
- 12:39
- 浏览 (2175)
- 评论 (5)
- 发布在 Groovy on Grails 圈子
- 相关推荐
评论
sungaofei
2007-11-15
啥时候又把博客搬到这了,还混成了infoq的编辑。老哥我要离开西安了,有时间一块喝个酒吧
foxgem
2007-06-07
会,缺省grails中使用的内存数据库。
yanhua
2007-06-07
请问foxgem,new Category(name: "Test1", parent: null).save() 会不会操作数据库呢?
foxgem
2007-06-04
最简单的做法就是在ant中去调用grails test,因为它本身就是一个命令。这个ant有很多例子。
agile_boy
2007-06-01
对,通过运行grails test,运行测试还是很方便的,不过目前我还不知道如何集成到ant,maven等环境中。。。
发表评论
- 浏览: 6850 次
- 性别:


- 详细资料
搜索本博客
最近加入圈子
链接
最新评论
-
Maven2 + Subversion + Cr ...
请问一下,你的ccworkplace是建在哪个路径下的?谢谢
-- by kevin_gzhz -
Grails中的Controller单元 ...
啥时候又把博客搬到这了,还混成了infoq的编辑。老哥我要离开西安了,有时间一块 ...
-- by sungaofei -
Grails中的Controller单元 ...
会,缺省grails中使用的内存数据库。
-- by foxgem -
Grails中的Controller单元 ...
请问foxgem,new Category(name: "Test1", par ...
-- by yanhua -
Grails中的Controller单元 ...
最简单的做法就是在ant中去调用grails test,因为它本身就是一个命令。 ...
-- by foxgem






评论排行榜