Show List
JUnit annotations
JUnit provides a set of annotations that allow you to define and control the behavior of your tests. These annotations are used to identify test methods, set up test fixtures, and manage test execution. Here are some of the most commonly used JUnit annotations:
@Test
: Used to identify a method as a JUnit test method. The@Test
annotation is used to specify the code that should be executed as a test. For example:
import org.junit.Test;
public class ExampleTest {
@Test
public void testExample() {
int a = 1;
int b = 2;
assertEquals(3, a + b);
}
}
@Before
: Used to specify a method that should be run before each test method in a test class. The@Before
method is typically used to set up any test fixtures or data that is required for the tests. For example:
import org.junit.Before;
import org.junit.Test;
public class ExampleTest {
private List<Integer> numbers;
@Before
public void setUp() {
numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
}
@Test
public void testListContainsThree() {
assertEquals(3, numbers.size());
}
}
@After
: Used to specify a method that should be run after each test method in a test class. The@After
method is typically used to clean up any resources or data that was created for the tests. For example:
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ExampleTest {
private List<Integer> numbers;
@Before
public void setUp() {
numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
}
@Test
public void testListContainsThree() {
assertEquals(3, numbers.size());
}
@After
public void tearDown() {
numbers = null;
}
}
@BeforeClass
: Used to specify a method that should be run once before any test methods in a test class. The@BeforeClass
method is typically used to set up any resources or data that is required for all tests in the class. For example:
import org.junit.BeforeClass;
import org.junit.Test;
public class ExampleTest {
private static List<Integer> numbers;
@BeforeClass
public static void setUpClass() {
numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
}
@Test
public void testListContainsThree() {
assertEquals(3, numbers.size());
}
}
@AfterClass
: Used to specify a method that should be run once after all test methods in a test class. The@AfterClass
method is typically used
Leave a Comment