Verify addition method returns correct sum
Preconditions (2)
✅ Expected Result: The test passes confirming that add(2, 3) returns 5
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class Calculator { public static int add(int a, int b) { return a + b; } } public class CalculatorTest { @Test void testAdd() { int result = Calculator.add(2, 3); assertEquals(5, result, "2 + 3 should equal 5"); } }
The @Test annotation marks the method testAdd as a test method for JUnit to run.
Inside testAdd, we call the add method from the Calculator class with inputs 2 and 3.
We then use assertEquals to check if the result is 5. If it is, the test passes; otherwise, it fails.
This simple structure shows how @Test helps JUnit identify and run test methods automatically.
Now add data-driven testing with 3 different input pairs for the add method
@Test annotation in JUnit?@Test@Test annotation tells JUnit which methods are test cases to execute.@Test marks test methods [OK]@Test means 'run this method as test' [OK]@Test changes method visibility@Test with import statements@Test sets return type@Test?import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class SampleTest {
@Test
public void checkSum() {
int result = 2 + 3;
assertEquals(5, result);
}
}assertEquals(5, result) will pass.import org.junit.jupiter.api.Test;
public class ErrorTest {
@Test
private void testHidden() {
// test code
}
}@Test for this purpose in JUnit 5?assertThrows() inside @Test methods to check exceptions.@Test(expected = Exception.class) annotation parameter is from JUnit 4 and invalid in JUnit 5. Add throws Exception to the test method signature only declares exception, not tests it. Write a try-catch block without @Test misses @Test.@Test with assertThrows() inside the method -> Option D@Test(expected=) in JUnit 5@Test annotationPass the test and this pattern moves unknown