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
@Testmeans the method won't run as a test. - Test methods must be
public voidwith no parameters; otherwise, JUnit will ignore or error. - Not importing
org.junit.jupiter.api.Testor 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
| Aspect | Details |
|---|---|
| Annotation | @Test |
| Method signature | public void methodName() |
| Import | org.junit.jupiter.api.Test |
| Purpose | Marks method as a test case |
| Run | JUnit 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.