教程 > junit 教程 > 阅读:26

junit 执行过程——迹忆客-ag捕鱼王app官网

本教程阐明了 junit 中的方法执行过程,即哪一个方法首先被调用,哪一个方法在一个方法之后调用。以下为 junit 测试方法的 api,并且会用例子来说明。

在目录 c:\ > junit_workspace 创建一个 java 类文件命名为 junitannotation.java 来测试注释程序。

junitannotation.java

import org.junit.after;
import org.junit.afterclass;
import org.junit.before;
import org.junit.beforeclass;
import org.junit.ignore;
import org.junit.test;
public class executionprocedurejunit {
   //execute only once, in the starting 
   @beforeclass
   public static void beforeclass() {
      system.out.println("in before class");
   }
   //execute only once, in the end
   @afterclass
   public static void  afterclass() {
      system.out.println("in after class");
   }
   //execute for each test, before executing test
   @before
   public void before() {
      system.out.println("in before");
   }
   //execute for each test, after executing test
   @after
   public void after() {
      system.out.println("in after");
   }
   //test case 1
   @test
   public void testcase1() {
      system.out.println("in test case 1");
   }
   //test case 2
   @test
   public void testcase2() {
      system.out.println("in test case 2");
   }
}

接下来,让我们在目录 c:\ > junit_workspace 中创建一个 java 类文件 testrunner.java 来执行注释程序。

testrunner.java

import org.junit.runner.junitcore;
import org.junit.runner.result;
import org.junit.runner.notification.failure;
public class testrunner {
   public static void main(string[] args) {
      result result = junitcore.runclasses(executionprocedurejunit.class);
      for (failure failure : result.getfailures()) {
         system.out.println(failure.tostring());
      }
      system.out.println(result.wassuccessful());
   }
} 

使用 javac 命令来编译 test casetest runner 类。

c:\junit_workspace>javac executionprocedurejunit.java testrunner.java

现在运行 test runner 它会自动运行定义在 test case 类中的测试样例。

c:\junit_workspace>java testrunner

验证输出

in before class
in before
in test case 1
in after
in before
in test case 2
in after
in after class

观察以上的输出,这是 junit 执行过程:

  • beforeclass() 方法首先执行,并且只执行一次。
  • afterclass() 方法最后执行,并且只执行一次。
  • before() 方法针对每一个测试用例执行,但是是在执行测试用例之前。
  • after() 方法针对每一个测试用例执行,但是是在执行测试用例之后。
  • before() 方法和 after() 方法之间,执行每一个测试用例。

查看笔记

扫码一下
查看教程更方便
网站地图