Spring单元测试利器 -- testng

TESTNG使Java单元测试轻而易举

深入了解testng,请访问:http://www.yiibai.com/html/testng/2013/0914295.html

在每个软件包的构造阶段,测试阶段都扮演扮演者中心角色。过去那种先编译再测试的日子已经一去不去不返,现在大多数开发人员现在认识到需要采用编码和测试彼此交织、同步推进的软件方法论,以便尽早发现bug,在开发过程开始的时候就识别出风险。

TESTNG快速进阶

1、TestNG概述

    TestNG是一种基于注解的测试框架,通过添加诸如灵活的装置、测试分类、参数测试、依赖方法、数据驱动等特性来克服JUnit的一些不足之处。由于TestNG可以轻松地将开发人员测试分类成单元组

组件组合系统组,因此能够使构建时间保持在可管理的范围内。通过使用group注释和多重Ant任务,测试组可以不同的频率运行在一台工作站之上或者持续集成的环境中。

    编写一个测试的过程有3个典型步骤

    (1)编写测试的业务逻辑并在代码中插入TestNG注解

    (2)将测试信息添加到testng.xml或者build.xml中

    (3)运行TestNG

2、TestNG声明周期

    TestNG测试用例的完整生命周期要经历一下阶段:类级初始化资源处理、方法级初始化资源处理、执行测试用例中的方法、方法级销毁资源处理、类级销毁资源处理。

3、使用TestNG

    TestNG中使用@Test注解来标注一个测试方法。此外可以采用JDK5静态导入功能导入断言Assert类,这样就可以很方便的在测试方法中使用断言了。

package org.worm.biz;
import org.testng.annotations.Test;
import org.worm.util.StringUtil;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
public class StringUtilTest {
  @Test
  public void f() {
   System.out.println("this is TestNG test case");
  }
  @Test
  public void testStr(){
   String trimStr = StringUtil.getTrimStr(" foo ");
   System.out.println("测试用:"+trimStr);
  }
  @Test
  public void testWithAssert(){
   assert "foo".equals(StringUtil.getTrimStr(" foo "));
  }
  @BeforeClass
  public void beforeClass() {
   System.out.println("this is before test method");
  }
  @AfterClass
  public void afterClass() {
   System.out.println("this is after test method");
  }
}

但是,在运行测试之前,必须用特殊的XML文件配置TestNG,习惯上把这个文件命名为testng.xml。这个文件首先定义测试套件Suite,这个套件里只包含一个测试Test,这个测试由StringUtilTest类完成。

<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" parallel="false">
  <test name="Test">
    <classes>
      <class name="org.worm.biz.StringUtilTest"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->

测试结果:

[TestNG] Running:
  D:\workspace\workspace_worm\worm-parent\worm-biz\src\test\java\testng.xml
this is before test method
this is TestNG test case
测试用:foo
this is after test method
===============================================
Suite
Total tests run: 3, Failures: 0, Skips: 0
===============================================
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章