Grails 进阶: 单元测试 ( unit testing in Grails )

访问量: 2276

假如,我们有一个controller: controllers/dashboard/StatusController.groovy  (Assuming we have a controller ) 

  1 package dashboard
  2 
  3 class StatusController {
  4 
  5     def index() {
  6     }
  7 
  8  }

我们要给它 加上单元测试,该怎么做呢? (how to add unit test for it? )

1. 建立文件: test/unit/dashboard/StatusControllerTests.groovy ( create a file )

  1 package dashboard
  2 import grails.test.mixin.*
  3 import org.junit.*
  4 
  5 @TestFor(StatusController)
  6 class StatusControllerTests {
  7 
  8     void testIndex () {
  9         controller.index()
 10         assertEquals "bar", controller.response.contentAsString
 11     }
 12 }

2. 运行: grails test-app StatusController 或者 $ grails test-app *Controller ( run $ grails test-app *Controller )

sg552@siwei-moto:~/workspace/dashborad$ grails test-app StatusController
| Running 1 unit test... 1 of 1
| Failure:  testIndex(dashboard.StatusControllerTests)
|  junit.framework.ComparisonFailure: expected:<[bar]> but was:<[]>
	at junit.framework.Assert.assertEquals(Assert.java:85)
	at dashboard.StatusControllerTests.testIndex(StatusControllerTests.groovy:16)
| Completed 1 unit test, 1 failed in 6425ms
| Packaging Grails application.....
| Tests FAILED  - view reports in /home/sg552/workspace/dashborad/target/test-reports

3. 但是尚未结束,当调用model的自动方法时出错:

| Failure:  testInfo(dashboard.StatusControllerTests)
|  groovy.lang.MissingMethodException: No signature of method: dashboard.StationInfo.get() is applicable for argument types: () values: []
Possible solutions: get(java.io.Serializable), getId(), getIp(), grep(), grep(java.lang.Object), getAt(java.lang.String)
	at dashboard.StatusController.getResult(StatusController.groovy:14)
        ......

运行 $ grails test-app StatusController --integration 之后,就可以解决这个问题。参考: http://stackoverflow.com/a/9255043

3. 进一步: grails-app/conf/DataSource.groovy 可以看到数据库配置,相当于 rails 的 database.yml ( grails-app/conf/DataSource.groovy == database.yml in Rails )

一点体会: Grails运行单元测试的速度太慢了。 跑了一个UT下来,从回车到结果显示结束,耗费近60秒的时间。 实际上我过了4秒就等不及开始溜号了。 ( However it's much slower that running Tests in Grails than in Rails. It takes almost 60 seconds to execute a unit tests while I lost my focus in 4 seconds )

RAILS一般都可以在10秒内启动,估计省去了GRAILS的编译过程。( and in Rails the total process often cost less than 10 seconds)

订阅/RSS Feed

Subscribe

分类/category