天天看点

如何写好Junit单元测试

 最近准备做一个junit测试的项目,先浅显研究了一下junit4,稍作记录。

  junit4通过annotation来表明各个方法的作用,最常用到的是

  @before :同一个测试类中的每个测试方法之前运行一次,必须是public void 非 static的方法,一个类中可以有多个

  @after :同一个测试类中的每个测试方法之后运行一次,必须是public void非 static的方法,一个类中可以有多个

  @afterclass : 同一个测试类中的所有测试方法运行之后运行一次,必须是public static void的方法,适合做一些所有测试方法跑完后的资源释放工作

  @ignore :暂时不需要跑的方法

  试着写了个测试类来使用到上述6个annotation

public class calculator  {

/**

* @param args

*/

public calculator(){

}

public int add(int arg1, int arg2){

return (arg1 + arg2);

public int minus(int arg1, int arg2){

return (arg1 - arg2);

import java.util.date;

import org.junit.*;

public class testbase {

private static calculator cal;

@beforeclass

public static void beforeclass(){

system.out.println("beforeclass");

cal = new calculator();

@before

public void before1(){

system.out.println(new date());

public void before2(){

system.out.println("before 2");

@test

public void test1(){

system.out.println("test 1");

assert.assertequals(2, cal.add(1, 1));

public void test2(){

system.out.println("test 2");

assert.asserttrue(1 == cal.minus(2, 1));

@ignore

public void test3(){

system.out.println("test 3");

@after

public void after1(){

public void after2(){

system.out.println("after 2");

@afterclass

public static void afterclass(){

system.out.println("afterclass");

  运行结果如下

beforeclass

before 2

thu nov 07 21:35:00 cst 2013

test 1

after 2

test 2

afterclass

  可以看出beforeclass和afterclass都只执行一遍,before和after 在每个case运行前后都执行一遍,多个before或after运行顺序与放置顺序没有必然联系。标识为ignore的方法没有被执行。

最新内容请见作者的github页:http://qaseven.github.io/

继续阅读