JUnit - 執(zhí)行過程

2022-10-08 11:04 更新

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

在目錄 C:\ > JUNIT_WORKSPACE 創(chuàng)建一個 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)建一個 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)在運行 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 執(zhí)行過程:

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


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號