鍍金池/ 教程/ Java/ JUnit - 執(zhí)行過程
JUnit - 參數(shù)化測試
JUnit - 執(zhí)行過程
JUnit - 執(zhí)行測試
JUnit - 概述
JUnit - 測試框架
JUnit - 套件測試
Junit - 環(huán)境設(shè)置
JUnit - 忽略測試
JUnit - 使用斷言
JUnit - Eclipse 插件
JUnit - 時(shí)間測試
JUnit - 編寫測試
JUnit - 框架擴(kuò)展
JUnit - API
JUnit - 異常測試
JUnit - ANT 插件
JUnit - 基本用法

JUnit - 執(zhí)行過程

本教程闡明了 JUnit 中的方法執(zhí)行過程,即哪一個(gè)方法首先被調(diào)用,哪一個(gè)方法在一個(gè)方法之后調(diào)用。以下為 JUnit 測試方法的 API,并且會(huì)用例子來說明。

在目錄 C:\ > JUNIT_WORKSPACE 創(chuàng)建一個(gè) 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 中創(chuàng)建一個(gè) java 類文件 TestRunner.java 來執(zhí)行注釋程序。

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 case 和 Test Runner 類。

C:\JUNIT_WORKSPACE>javac ExecutionProcedureJunit.java TestRunner.java

現(xiàn)在運(yùn)行 Test Runner 它會(huì)自動(dòng)運(yùn)行定義在 Test Case 類中的測試樣例。

C:\JUNIT_WORKSPACE>java TestRunner

驗(yàn)證輸出

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

觀察以上的輸出,這是 JUnite 執(zhí)行過程:

  • beforeClass() 方法首先執(zhí)行,并且只執(zhí)行一次。
  • afterClass() 方法最后執(zhí)行,并且只執(zhí)行一次。
  • before() 方法針對每一個(gè)測試用例執(zhí)行,但是是在執(zhí)行測試用例之前。
  • after() 方法針對每一個(gè)測試用例執(zhí)行,但是是在執(zhí)行測試用例之后。
  • 在 before() 方法和 after() 方法之間,執(zhí)行每一個(gè)測試用例。