Complete the code to create a basic JUnit test method.
public class CalculatorTest { @Test public void testAddition() { Calculator calc = new Calculator(); int result = calc.add(2, 3); assertEquals([1], result); } }
The expected result of adding 2 and 3 is 5, so assertEquals(5, result) is correct.
Complete the code to assert that a list contains a specific element.
import static org.junit.jupiter.api.Assertions.*; import java.util.List; public class ListTest { @Test public void testContainsElement() { List<String> fruits = List.of("apple", "banana", "cherry"); assertTrue(fruits.[1]("banana")); } }
The contains method checks if the list has the specified element.
Fix the error in the assertion to correctly compare two objects for equality.
public class PersonTest { @Test public void testPersonEquality() { Person p1 = new Person("Alice", 30); Person p2 = new Person("Alice", 30); assert[1](p1, p2); } }
The correct JUnit assertion method to check object equality is assertEquals.
Fill both blanks to create a parameterized test method that runs with multiple inputs.
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; public class NumberTest { @ParameterizedTest @ValueSource([1]) public void testIsPositive(int number) { assertTrue(number [2] 0); } }
ints =) in @ValueSource.>= instead of >, which would accept zero as positive.The @ValueSource annotation requires a type-specific attribute such as ints = {1, 2, 3} for integer values. The assertion uses > to verify the number is positive (greater than zero).
Fill all three blanks to write a test that verifies a map contains a key with a specific value.
import static org.junit.jupiter.api.Assertions.*; import java.util.Map; public class MapTest { @Test public void testMapKeyValue() { Map<String, Integer> ages = Map.of("Bob", 25, "Carol", 30); assertTrue(ages.[1]("Bob") && ages.get("Bob") [2] [3]); } }
The method containsKey checks if the map has the key. To compare the value, equals is used to compare with 25.