May 15, 2021 jUnit
This tutorial illustrates the method execution procedure in JUnit, which method is called first and which method is called after a method. The following is the API for the JUnit test method, which is illustraten by example.
In Directory C: This is JUNIT_WORKSPACE to test the annotation program by creating a java class file .java JunitAnnotation.
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");
}
}
Next, let's go to Directory C: The user JUNIT_WORKSPACE java class file TestRunner in the .java to perform the annotation program.
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());
}
}
Use the javac command to compile the Test case and Test Runner classes.
C:\JUNIT_WORKSPACE>javac ExecutionProcedureJunit.java TestRunner.java
Now run Test Runner and it will automatically run the test samples defined in the Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output
in before class
in before
in test case 1
in after
in before
in test case 2
in after
in after class
Observe the output above, which is the JUnite execution: