Sobes.tech
Junior — Middle

What tests would you create to check the behavior of the List interface?

sobes.tech AI

Answer from AI

To test the List interface in Java, you should create the following types of tests:

  • Add element tests: verify that elements are added correctly and the list size increases.
  • Remove element tests: removal by index and by object, verify the correctness of size and content.
  • Access by index tests: get element, check for exceptions when out of bounds.
  • Modify element tests: set new value by index.
  • Search tests: check methods contains, indexOf, lastIndexOf.
  • Iteration tests: verify correct traversal of elements via iterator.
  • Boundary tests: work with an empty list, adding null (if supported).

Example of a simple test using JUnit:

@Test
public void testAddAndGetSize() {
    List<String> list = new ArrayList<>();
    assertEquals(0, list.size());
    list.add("test");
    assertEquals(1, list.size());
    assertEquals("test", list.get(0));
}

This helps ensure the List implementation behaves correctly.