對于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.kjueaiud.com/