Complete the code to create a basic JUnit test method.
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class CalculatorTest { @[1] void testAddition() { int result = 2 + 3; assertEquals(5, result); } }
The @Test annotation marks a method as a test method in JUnit 5.
Complete the assertion to check if two strings are equal.
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.[1]; public class StringTest { @Test void testEquality() { String expected = "hello"; String actual = "hello"; [1](expected, actual); } }
assertEquals checks if two values are equal, which is perfect for comparing strings.
Fix the error in the test method to correctly expect an exception.
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertThrows; public class ExceptionTest { @Test void testException() { assertThrows([1].class, () -> { Integer.parseInt("abc"); }); } }
The NumberFormatException is thrown when parsing a non-numeric string to an integer.
Fill in the blank to create a parameterized test that runs with multiple inputs.
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import static org.junit.jupiter.api.Assertions.assertTrue; public class ParameterizedTestExample { @[1] @ValueSource(strings = {"racecar", "radar", "level"}) void testPalindrome(String word) { assertTrue(word.equals(new StringBuilder(word).reverse().toString())); } }
The @ParameterizedTest annotation tells JUnit to run the test multiple times with different inputs.
Fill all three blanks to create a test suite that runs multiple test classes.
import org.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; @Suite @SelectClasses([1].class, [2].class) public class [3] { }
The @SelectClasses annotation lists test classes to run. The class name for the suite is AllTests.