📅  最后修改于: 2020-11-12 04:39:20             🧑  作者: Mango
本章介绍了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
现在运行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
参见上面的输出。执行过程如下-