Grails中的Controller单元测试
对于Controller的 单元测试 ,Grails也提供了很方便的支持,使得书写非常简单,有代码为证: 单元测试代码 class CategoryControllerTests extends Groovy TestCase { void setUp(){ deftest1= new Category(name: "Test1" ,parent: null ).save() deftest2=
对于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进行到底。
原文转自:http://www.ltesting.net