JUnit执行过程

本文解释了JUnit中方法的执行过程,定义了方法调用的顺序。下面举例说明 JUnit 测试 API 方法的执行过程。

创建一个名为 ExecutionProcedureJunit.java 的 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");
   }
}

接下来,创建一个名为 TestRunner.java 的 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());
   }
} 

输出如下:

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

查看上面的输出。执行过程如下

首先,beforeClass() 方法只执行一次。 

afterClass() 方法只执行一次。

before() 方法针对每个测试用例执行,但在执行测试用例之前。 

after() 方法针对每个测试用例执行,但在测试用例执行之后。 

在 before() 和 after() 之间,执行每个测试用例。

其实,通过JUnit的执行注解还是很容易理解这些执行过程的,最重要的是要学会怎么使用的问题。

版权声明:著作权归作者所有。

thumb_up 0 | star_outline 0 | textsms 0