What tests need to be created to verify the correctness of adding an element to an ArrayList?
sobes.tech AI
Answer from AI
To verify the correctness of adding an element to an ArrayList, the following tests should be created:
-
Adding a single element — check that after adding, the list size increases by 1, and the element is at the expected index.
-
Adding multiple elements — ensure that all added elements are present in the list in the correct order.
-
Adding null (if allowed) — verify that the list correctly stores null elements.
-
Adding an element to an empty list — check that the element is successfully added and the list size becomes 1.
-
Adding an element in the middle of the list (if using the add method with an index) — verify that the element is inserted at the correct position and other elements are shifted.
Example of a simple JUnit test:
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
public class ArrayListTest {
@Test
public void testAddElement() {
ArrayList<String> list = new ArrayList<>();
list.add("test");
assertEquals(1, list.size());
assertEquals("test", list.get(0));
}
}