Using @Test in JUnit
In JUnit, @Test is an annotation that marks a method as a test method. When you run your tests, JUnit looks for methods annotated with @Test and executes them automatically.
1. Add the Correct Import
For JUnit 5, use:
import org.junit.jupiter.api.Test;
You will usually also import assertions such as:
import static org.junit.jupiter.api.Assertions.*;
2. Basic Example
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CalculatorTest {
@Test
void addTwoNumbers() {
int result = 10 + 15;
assertEquals(25, result);
}
}
Here:
@Testtells JUnit this method should be run as a test.assertEquals(25, result)checks that the actual result is25.- If the assertion passes, the test passes.
- If the assertion fails, the test fails.
3. Common JUnit 5 Assertions
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ExampleTest {
@Test
void assertionsExample() {
String message = "Hello JUnit";
assertNotNull(message);
assertTrue(message.contains("JUnit"));
assertEquals("Hello JUnit", message);
}
}
Common assertions include:
| Assertion | Purpose |
|---|---|
assertEquals(expected, actual) |
Checks that two values are equal |
assertTrue(condition) |
Checks that a condition is true |
assertFalse(condition) |
Checks that a condition is false |
assertNotNull(value) |
Checks that a value is not null |
assertThrows(...) |
Checks that code throws an expected exception |
4. Testing Exceptions
Use assertThrows() when you expect code to throw an exception:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
class DivisionTest {
@Test
void divideByZeroThrowsException() {
assertThrows(ArithmeticException.class, () -> {
int result = 10 / 0;
});
}
}
5. JUnit 5 Test Method Rules
In JUnit 5, test methods usually:
- Are annotated with
@Test - Return
void - Do not need to be
public - Should contain assertions
- Should have descriptive names
Example:
@Test
void shouldReturnSumWhenAddingTwoNumbers() {
assertEquals(5, 2 + 3);
}
6. JUnit 4 vs. JUnit 5 Import
Be careful: JUnit 4 and JUnit 5 use different @Test imports.
JUnit 5
import org.junit.jupiter.api.Test;
JUnit 4
import org.junit.Test;
For new projects, JUnit 5 is generally recommended.
7. Running the Test
You can run JUnit tests from:
- Your IDE, such as IntelliJ IDEA or Eclipse
- Maven
- Gradle
With Maven:
mvn test
With Gradle:
gradle test
or:
./gradlew test
Summary
Use @Test above a method to tell JUnit, “this is a test.”
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class MyTest {
@Test
void simpleTest() {
assertEquals(4, 2 + 2);
}
}
That method will be discovered and run by JUnit as part of your test suite.
