`

Play上写单元测试实践

阅读更多

写在前面

TDD,是最难在团队中推行的XP实践,有以下的原因

1、TDD需要调整个人开发的过程,从 code - test - debug 变成 test - code,改变了个人开发习惯,要知道,习惯是最难改变的

2、TDD耗时间(暂且不论对还是不对)

3、不写单元测试对项目没有立杆见影的坏影响(或者有了,但是不会有人觉察)

 

  那,这么多的缺点,为什么还是这么多人推荐TDD呢?因为TDD带来的好处是敏捷开发需要的:

敏捷只需要适度的设计,通过不断的重构达成完美的程序,而重构就需要单元测试这根保险绳。

 

在目前国内的研发团队中,真正能采用TDD的团队还不多,有些是因为项目组不要求,有些是因为难以推行而中止。

 

其实,只要踏出第一步,你或许会被单元测试迷住,喜欢上那种绿色代表的安稳的感觉。

下面,我介绍一下在我们项目中写的单元测试的情况

 

Play的三种测试

Play集成了Junit和Selenium作为单元测试的框架。

 

Unit test

 

public class AModelTest extends UnitTest {
    @Before
    public void before() {
        
    }

    @After
    public void after() {

    }

    @Test
    public void testInsert() {
   }
}
 

 

  unit test使用Junit框架进行编写,一般使用unit test进行model层的单元测试代码编写。

 

Functional test

  控制器层用Functional test进行测试

 

import play.test.*;
import play.mvc.*;
import play.mvc.Http.*;
import org.junit.*;
 
public class ApplicationTest extends FunctionalTest {
     
    @Test
    public void testTheHomePage() {
        Response response = GET("/");
        assertStatus(200, response);
    }
     
}
 

 

Selenium test

  selenium是一个可以直接调用浏览器进行测试的一个测试框架,在Play上可以用selenium进行页面的自动化测试。

下面是selenium的一个代码例子:

 

#{selenium 'Test security'}
 
    // Try to log in the administration area
    clearSession()
    open('/admin')
    assertTextPresent('Login')
    type('login', 'admin')
    type('password', 'secret')
    clickAndWait('signin')
 
    // Verify that the user in correctly logged in
    assertText('success', 'Welcom admin!')
 
#{/selenium}
 

 

 

运行测试

 

  使用play test 运行项目

  访问http://ip:端口/@tests

 

  play的测试运行页面会把以上三种测试类型的测试在页面中列出来,在页面中可以直接运行。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics