0
0
JunitHow-ToBeginner ยท 3 min read

How to Use @Test Annotation in JUnit for Unit Testing

In JUnit, use the @Test annotation to mark a method as a test case. This tells JUnit to run that method as a test when executing your test class.
๐Ÿ“

Syntax

The @Test annotation is placed above a method to indicate it is a test method. The method should be public, return void, and take no parameters.

JUnit will automatically run all methods annotated with @Test when you run the test class.

java
import org.junit.jupiter.api.Test;

public class ExampleTest {
    @Test
    public void sampleTest() {
        // test code here
    }
}
๐Ÿ’ป

Example

This example shows a simple test method using @Test that checks if the sum of two numbers is correct using an assertion.

java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class CalculatorTest {
    @Test
    public void additionTest() {
        int result = 2 + 3;
        assertEquals(5, result, "2 + 3 should equal 5");
    }
}
Output
Test passed successfully with no errors.
โš ๏ธ

Common Pitfalls

  • Forgetting to add @Test means the method won't run as a test.
  • Test methods must be public void with no parameters; otherwise, JUnit will ignore or error.
  • Not importing org.junit.jupiter.api.Test or mixing JUnit 4 and 5 annotations can cause confusion.
java
import org.junit.jupiter.api.Test;

public class WrongTest {
    // This method will NOT run as a test because @Test is missing
    public void missingAnnotation() {
        // test code
    }

    // Correct usage
    @Test
    public void correctTest() {
        // test code
    }
}
Output
Only 'correctTest' runs as a test; 'missingAnnotation' is ignored.
๐Ÿ“Š

Quick Reference

AspectDetails
Annotation@Test
Method signaturepublic void methodName()
Importorg.junit.jupiter.api.Test
PurposeMarks method as a test case
RunJUnit runs all @Test methods automatically
โœ…

Key Takeaways

Use @Test above methods to mark them as test cases in JUnit.
Test methods must be public, void, and have no parameters.
Always import org.junit.jupiter.api.Test for JUnit 5 tests.
Without @Test, methods won't run as tests.
Use assertions inside @Test methods to verify behavior.