- Published on
JUnit TestCase lifecycle
- Authors
- Name
- Arnaud Ferrand
- @arferrand
JUnit TestCase lifecycle
Maven dependency :
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
class name is suffixed by Test, I don't need to write a TestSuite class. All endinf Test name class are executed.
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Created by aferrand on 01/06/2015.
*/
public class ExampleUnitTest {
@BeforeClass
public static void oneTimeSetUp() {
System.out.println("Before all test cases");
}
@AfterClass
public static void oneTimeTearDown() {
System.out.println("After all test cases");
}
@Before
public void setUp() throws Exception {
System.out.println("Before each test case");
}
@After
public void tearDown() throws Exception {
System.out.println("After each test case");
}
@Test
public void testA() {
System.out.println("Test A");
}
@Test
public void testB() {
System.out.println("Test B");
}
}
After If you allocate external resources in a Before method you need to release them after the test runs. AfterClass If you allocate expensive external resources in a BeforeClass method you need to release them after all the tests in the class have run. Before When writing tests, it is common to find that several tests need similar objects created before they can run. BeforeClass Sometimes several tests need to share computationally expensive setup (like logging into a database). Test The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case.
The @BeforeClass and @AfterClass annotations are used to specify the methods which are executed once for all test cases. The @Before and @After* annotations are used to specify the methods which are invoked before and after execution of single test case. The *@Test_ annotation is used to specify a single test case.
Output
Running ExampleUnitTest
Before all test cases
Before each test case
Test A
After each test case
Before each test case
Test B
After each test case
After all test cases