0
0
JUnittesting~5 mins

@Test annotation in JUnit

Choose your learning style9 modes available
Introduction

The @Test annotation tells JUnit which methods are test cases. It helps run tests automatically without manual calls.

When you want to check if a method in your code works correctly.
When you want to run multiple tests automatically in one go.
When you want to mark a method as a test so JUnit can report pass or fail.
When you want to organize your tests clearly in your test class.
When you want to use assertions inside a method to verify expected results.
Syntax
JUnit
@Test
public void testMethodName() {
    // test code here
}

The method annotated with @Test must be public and void.

No arguments are allowed in the test method.

Examples
This test checks if 2 + 3 equals 5.
JUnit
@Test
public void additionTest() {
    int sum = 2 + 3;
    assertEquals(5, sum);
}
This test checks that the string is not null.
JUnit
@Test
public void stringTest() {
    String text = "hello";
    assertNotNull(text);
}
Sample Program

This test class has one test method multiplyTest that checks if 4 times 5 equals 20.

JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class CalculatorTest {

    @Test
    public void multiplyTest() {
        int result = 4 * 5;
        assertEquals(20, result);
    }
}
OutputSuccess
Important Notes

Use @Test to mark each test method clearly.

JUnit 5 uses org.junit.jupiter.api.Test package.

Assertions like assertEquals help verify expected results inside @Test methods.

Summary

@Test marks methods as test cases for JUnit to run.

Test methods must be public, void, and take no parameters.

Use assertions inside @Test methods to check results.