What is the purpose of the @Test annotation?

The @Test annotation marks a method as a test case that the JUnit framework should discover and execute automatically as part of a test run.

Key Points: • Any public (JUnit 4) or package-private (JUnit 5) method annotated with @Test is treated as an independent, runnable unit test. • JUnit's test runner scans for @Test methods, executes each one, and reports pass/fail results. • A test method typically follows the arrange-act-assert pattern and uses assertion methods to verify expected outcomes. • If a @Test method throws any uncaught exception (including a failed assertion), JUnit marks that test as failed. • @Test methods should be independent of each other so tests can run in any order without side effects.

Example: Annotating a method calculatesSumCorrectly() with @Test tells JUnit to run it automatically during the build, checking that a Calculator's add() method returns the right result.

Code Example:

@Test
void calculatesSumCorrectly() {
    assertEquals(5, calculator.add(2, 3));
}

Interview Tip: A concise interview answer is:

"@Test marks a method as a unit test that JUnit should discover and run automatically. It's how the framework identifies which methods to execute, track pass/fail results for, and report on, without needing a main method or manual invocation."