Test Overview
This test uses the @Test annotation to mark a method as a test case. It verifies that the addition of two numbers returns the correct result.
This test uses the @Test annotation to mark a method as a test case. It verifies that the addition of two numbers returns the correct result.
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class CalculatorTest { @Test public void testAddition() { int a = 5; int b = 3; int result = a + b; assertEquals(8, result, "5 + 3 should equal 8"); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | JUnit test runner starts and scans for methods annotated with @Test | Test class CalculatorTest loaded with method testAddition marked as @Test | — | PASS |
| 2 | JUnit invokes the testAddition() method | Inside testAddition method, variables a=5 and b=3 initialized | — | PASS |
| 3 | Calculate result = a + b | result variable holds value 8 | — | PASS |
| 4 | Assert that result equals 8 using assertEquals | Comparing expected value 8 with actual result 8 | assertEquals(8, result) verifies values are equal | PASS |
| 5 | JUnit marks testAddition as PASSED and finishes test run | Test report shows testAddition PASSED | — | PASS |
@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