- JUnit 教程
- JUnit - 首頁
- JUnit - 概覽
- JUnit - 環境設定
- JUnit - 測試框架
- JUnit - 基本用法
- JUnit - API
- JUnit - 寫測試
- JUnit - 使用斷言
- JUnit - 執行過程
- JUnit - 執行測試
- JUnit - 套件測試
- JUnit - 忽略測試
- JUnit - 時間測試
- JUnit - 異常測試
- JUnit - 引數化測試
- JUnit - 與 Ant 插接
- JUnit - 與 Eclipse 插接
- JUnit - 擴充套件
- JUnit 有用資源
- JUnit - 問答
- JUnit - 快速指南
- JUnit - 有用資源
- JUnit - 討論
JUnit - 執行過程
本章解釋了 JUnit 中方法的執行過程,它定義了呼叫的方法的順序。下面討論的是 JUnit 測試 API 方法的執行過程及其示例。
在 C:\>JUNIT_WORKSPACE 中建立一個名為 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");
}
}
接下來,在 C:\>JUNIT_WORKSPACE 中建立一個名為 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());
}
}
使用 javac 編譯測試用例類和測試執行器類。
C:\JUNIT_WORKSPACE>javac ExecutionProcedureJunit.java TestRunner.java
現在執行測試執行器,該測試執行器將執行在提供的測試用例類中定義的測試用例。
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
見上述輸出,執行過程如下 -
- 首先,BeforeClass() 方法只執行一次。
- AfterClass() 方法只執行一次。
- Before() 方法對每個測試用例執行,但執行測試用例之前執行。
- After() 方法對每個測試用例執行,但在測試用例執行之後執行。
- 在 Before() 和 After() 之間,每個測試用例執行。
廣告