Java JUnit Test Methods
A JUnit test method is a method that JUnit runs as a single test. You create one by adding @Test to a method, and JUnit 6 offers more annotations to name, group, skip, repeat, time-limit and order your test methods.
This lesson covers the rules every JUnit test method must follow, how JUnit creates a fresh test instance for each method, and the annotations you will use most: @DisplayName, @Disabled, @Tag, @RepeatedTest, @Timeout, @Nested and @TestMethodOrder. It also shows assumptions and dynamic tests, and ends with a fully organized test class for a bank account. If you have not set up JUnit yet, start with Java JUnit Basics.
Rules for JUnit Test Methods
JUnit finds test methods by their annotation, not by their name. A method annotated with @Test must follow a few rules:
| Rule | Allowed | Not allowed |
|---|---|---|
| Visibility | public, protected, package-private | private |
| Static | Instance methods | static methods |
| Return type | void | Any other type (except for @TestFactory) |
| Parameters | None, or ones JUnit can supply such as TestInfo | Arbitrary parameters |
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
class TestMethodRulesTest {
@Test
void packagePrivateIsTheUsualStyle() {
assertEquals(4, 2 + 2);
}
@Test
public void publicAlsoWorks() {
assertEquals("JAVA", "java".toUpperCase());
}
@Test
void junitCanInjectTestInfo(TestInfo testInfo) {
System.out.println("Running: " + testInfo.getDisplayName());
assertEquals("junitCanInjectTestInfo(TestInfo)", testInfo.getDisplayName());
}
// Not a test: no @Test annotation, so JUnit ignores it
void helperMethod() {
}
}
Output (the println from the third test):
Running: junitCanInjectTestInfo(TestInfo)
How it works:
- All three annotated methods run as tests.
helperMethodhas no annotation, so JUnit treats it as an ordinary method you can call from tests. TestInfois a built-in parameter type. JUnit fills it with details about the current test, such as its display name and tags.- A
private,staticor non-voidmethod with@Testis not run. Current JUnit versions report such methods as a discovery problem instead of silently ignoring them.
Each Test Method Gets a New Test Instance
By default, JUnit creates a new instance of the test class for every test method. This keeps tests independent: a field changed by one test is not seen by the next.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class FreshInstanceTest {
private final List<String> cart = new ArrayList<>();
FreshInstanceTest() {
System.out.println("New test instance: " + System.identityHashCode(this));
}
@Test
void addOneItem() {
cart.add("Java Book");
assertEquals(1, cart.size());
}
@Test
void addTwoItems() {
cart.add("Keyboard");
cart.add("Mouse");
assertEquals(2, cart.size()); // not 3: the list from addOneItem is gone
}
}
Output (the numbers differ on each run):
New test instance: 1418385211
New test instance: 1282811396
How it works:
- The constructor runs twice, once per test method, so the two tests use two different
cartlists. addTwoItemsalways sees an empty list, whatever order the tests run in. That is why the size is 2, not 3.- You can change this with
@TestInstance(TestInstance.Lifecycle.PER_CLASS), which shares one instance for all methods. Shared state makes tests depend on each other, so keep the default unless you have a reason.
Note: Setup code that every test needs belongs in a
@BeforeEachmethod. You will learn the full lifecycle in JUnit Test Fixtures.
Name Test Methods With @DisplayName
Method names cannot contain spaces, so long names like withdrawMoreThanBalanceThrowsException are hard to read. @DisplayName gives a test a free-text name, and @DisplayNameGeneration can turn method names into sentences automatically.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.DisplayNameGeneration;
import org.junit.jupiter.api.DisplayNameGenerator;
import org.junit.jupiter.api.Test;
@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
class String_formatting_Test {
@Test
void trims_spaces_from_both_ends() {
assertEquals("gocourse", " gocourse ".strip());
}
@Test
@DisplayName("repeat() joins copies with no separator ✨")
void repeatMethod() {
assertEquals("abab", "ab".repeat(2));
}
}
Output in an IDE or the Console Launcher:
└─ String formatting Test ✔
├─ trims spaces from both ends ✔
└─ repeat() joins copies with no separator ✨ ✔
How it works:
ReplaceUnderscoresturnstrims_spaces_from_both_endsintotrims spaces from both ends, and does the same for the class name.- An explicit
@DisplayNamealways wins over the generator, so the second test shows the custom text, emoji included. - Display names only change reports. You still refer to the method name when running a single test from the command line.
| Generator | Example result for adds_two_numbers() |
|---|---|
Standard (default) | adds_two_numbers() |
Simple | adds_two_numbers (no parentheses when there are no parameters) |
ReplaceUnderscores | adds two numbers |
IndicativeSentences | Combines the class and method names into one sentence |
Skip Test Methods With @Disabled and Assumptions
Sometimes a test must not run: a feature is unfinished, or a test only makes sense on a certain operating system. @Disabled skips a test unconditionally, and assumptions skip it at runtime when a condition is not met.
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
class SkippingTestsTest {
@Test
@Disabled("Payment gateway sandbox is down until Monday - ticket PAY-142")
void chargesCardInSandbox() {
// not run
}
@Test
@EnabledOnOs(OS.LINUX)
void readsLinuxProcFile() {
assertTrue(java.nio.file.Files.exists(java.nio.file.Path.of("/proc/cpuinfo")));
}
@Test
void runsOnlyWhenApiKeyIsSet() {
String apiKey = System.getenv("PAYMENT_API_KEY");
assumeTrue(apiKey != null, "PAYMENT_API_KEY not set, skipping live API test");
assertTrue(apiKey.startsWith("sk_"));
}
}
Output of mvn test on Linux without PAYMENT_API_KEY (shortened):
[WARNING] Tests run: 3, Failures: 0, Errors: 0, Skipped: 2
How it works:
@Disabledskips the test every time. Always give a reason, so others know why it is off and when to turn it back on.@EnabledOnOs(OS.LINUX)runs the test only on Linux. Related annotations include@EnabledOnJre,@EnabledIfEnvironmentVariableand@DisabledIfSystemProperty.assumeTruechecks a condition inside the test. If it is false, JUnit aborts the test and reports it as skipped, not failed. On Linux,readsLinuxProcFilepasses and the other two are skipped.
Group Test Methods With @Tag
Tags label tests so you can run a subset, for example only fast tests on every commit and slow integration tests at night.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
class TaggedTest {
@Test
@Tag("fast")
void parsesPrice() {
assertEquals(499, Integer.parseInt("499"));
}
@Test
@Tag("slow")
@Tag("database")
void loadsAllCourses() throws InterruptedException {
Thread.sleep(500); // pretend to load from a database
assertEquals(12, 12);
}
}
Run only the fast tests, or everything except the slow ones:
mvn test -Dgroups=fast
mvn test -DexcludedGroups=slow
Output of mvn test -Dgroups=fast (shortened):
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
How it works:
- A test can have several tags.
loadsAllCoursesis bothslowanddatabase. - Surefire's
groupsandexcludedGroupsoptions filter by tag. Gradle usesuseJUnitPlatform { includeTags("fast") }. - Tags can also go on the class, and then apply to every test method inside it.
Repeat Test Methods With @RepeatedTest
@RepeatedTest runs the same method several times. It is handy for code that uses randomness or concurrency, where a bug may appear only occasionally.
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.security.SecureRandom;
import org.junit.jupiter.api.RepetitionInfo;
import org.junit.jupiter.api.RepeatedTest;
class RepeatedOtpTest {
private static final SecureRandom RANDOM = new SecureRandom();
static String newOtp() {
return String.format("%06d", RANDOM.nextInt(1_000_000));
}
@RepeatedTest(value = 5, name = "OTP check {currentRepetition}/{totalRepetitions}")
void otpIsAlwaysSixDigits(RepetitionInfo info) {
String otp = newOtp();
System.out.println(info.getCurrentRepetition() + ": " + otp);
assertTrue(otp.matches("\\d{6}"), "OTP was " + otp);
}
}
Output (codes differ on every run):
1: 048213
2: 731905
3: 600472
4: 915330
5: 002871
How it works:
@RepeatedTest(5)replaces@Testand runs the method five times, each as a separate test in the report.- The
namepattern produces display names such asOTP check 3/5. RepetitionInfotells the method which repetition is running. The OTP generator is the one from Java SecureRandom, and%06dkeeps leading zeros, so every run produces exactly six digits.
Limit Test Methods With @Timeout
A test that hangs blocks the whole build. @Timeout fails a test that takes longer than the given time.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
class TimeoutTest {
long slowFibonacci(int n) {
return n < 2 ? n : slowFibonacci(n - 1) + slowFibonacci(n - 2);
}
@Test
@Timeout(value = 2, unit = TimeUnit.SECONDS)
void smallFibonacciIsFast() {
assertEquals(6765, slowFibonacci(20));
}
@Test
@Timeout(value = 200, unit = TimeUnit.MILLISECONDS)
void hugeFibonacciIsTooSlow() {
assertEquals(12586269025L, slowFibonacci(50));
}
}
Output (shortened):
[ERROR] TimeoutTest.hugeFibonacciIsTooSlow:20 » Timeout hugeFibonacciIsTooSlow() timed out after 200 milliseconds
[ERROR] Tests run: 2, Failures: 0, Errors: 1, Skipped: 0
How it works:
slowFibonacci(20)finishes in milliseconds, well within two seconds.slowFibonacci(50)makes billions of calls. JUnit interrupts the test after 200 ms and reports aTimeoutException.- The default unit is seconds, so
@Timeout(5)means five seconds. Put@Timeouton a class to apply it to every test method.
Organize Test Methods With @Nested
@Nested lets you group related tests in inner classes. Each group can describe one situation, which makes large test classes much easier to read.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
@DisplayName("A stack")
class StackTest {
private Deque<String> stack;
@BeforeEach
void createStack() {
stack = new ArrayDeque<>();
}
@Nested
@DisplayName("when empty")
class WhenEmpty {
@Test
@DisplayName("is empty")
void isEmpty() {
assertTrue(stack.isEmpty());
}
@Test
@DisplayName("throws on pop")
void throwsOnPop() {
assertThrows(NoSuchElementException.class, stack::pop);
}
}
@Nested
@DisplayName("after pushing two elements")
class AfterPushing {
@BeforeEach
void pushTwo() {
stack.push("first");
stack.push("second");
}
@Test
@DisplayName("pop returns the last one pushed")
void popReturnsLast() {
assertEquals("second", stack.pop());
}
@Test
@DisplayName("has size 2")
void hasSizeTwo() {
assertEquals(2, stack.size());
}
}
}
Output in the Console Launcher:
└─ A stack ✔
├─ when empty ✔
│ ├─ is empty ✔
│ └─ throws on pop ✔
└─ after pushing two elements ✔
├─ pop returns the last one pushed ✔
└─ has size 2 ✔
How it works:
- A
@Nestedclass must be a non-static inner class, so it can use the outer class'sstackfield. - For each test, JUnit runs the outer
@BeforeEachfirst, then the inner one. Tests inAfterPushingtherefore start with a new stack holding two elements. - The report reads like a specification: "A stack, after pushing two elements, pop returns the last one pushed."
Control the Order of Test Methods
JUnit runs test methods in an order that is deterministic but intentionally not obvious. Good tests do not depend on order. When order matters for readability, such as in a step-by-step demo, use @TestMethodOrder.
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class OrderedStepsTest {
@Test
@Order(3)
void stepThreeCheckout() {
System.out.println("3. checkout");
assertTrue(true);
}
@Test
@Order(1)
void stepOneLogin() {
System.out.println("1. login");
assertTrue(true);
}
@Test
@Order(2)
void stepTwoAddToCart() {
System.out.println("2. add to cart");
assertTrue(true);
}
}
Output:
1. login
2. add to cart
3. checkout
How it works:
MethodOrderer.OrderAnnotationsorts methods by their@Ordervalue, lowest first, regardless of where they appear in the file.- Other orderers include
MethodName(alphabetical),DisplayNameandRandom.Randomis useful for exposing hidden dependencies between tests. - Each method still gets a new test instance, so ordering does not let tests share field values.
Generate Test Methods at Runtime With @TestFactory
A @TestFactory method does not test anything itself. It returns a collection or stream of DynamicTest objects, and JUnit runs each one as a separate test. This is useful when test cases come from data.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
class SlugDynamicTest {
static String toSlug(String title) {
return title.strip().toLowerCase().replaceAll("[^a-z0-9]+", "-").replaceAll("(^-|-$)", "");
}
@TestFactory
Stream<DynamicTest> slugsForLessonTitles() {
Map<String, String> cases = Map.of(
"Java Test Methods", "java-test-methods",
" KeyStore Basics ", "keystore-basics",
"C++ vs Java?", "c-vs-java");
return cases.entrySet().stream()
.map(entry -> dynamicTest("slug of '" + entry.getKey() + "'",
() -> assertEquals(entry.getValue(), toSlug(entry.getKey()))));
}
}
Output in the Console Launcher (order of the three may vary):
└─ slugsForLessonTitles() ✔
├─ slug of 'Java Test Methods' ✔
├─ slug of ' KeyStore Basics ' ✔
└─ slug of 'C++ vs Java?' ✔
How it works:
- A
@TestFactorymethod must return aStream,CollectionorIterableofDynamicTest(orDynamicContainer). This is the one case where a test method is notvoid. dynamicTest(name, executable)creates one test with a display name and the code to run.Map.ofhas no fixed order, so the three tests may appear in any order. For a fixed set of inputs, JUnit Parameterized Tests are often simpler.
Real-World Example: Organized Tests for a Bank Account
This example combines the annotations from this lesson into one test class for a small BankAccount.
package com.gocourse.bank;
public class BankAccount {
private final String owner;
private long balanceInPaise;
public BankAccount(String owner, long openingBalanceInPaise) {
if (openingBalanceInPaise < 0) {
throw new IllegalArgumentException("Opening balance cannot be negative");
}
this.owner = owner;
this.balanceInPaise = openingBalanceInPaise;
}
public void deposit(long amountInPaise) {
if (amountInPaise <= 0) {
throw new IllegalArgumentException("Deposit must be positive");
}
balanceInPaise += amountInPaise;
}
public void withdraw(long amountInPaise) {
if (amountInPaise <= 0) {
throw new IllegalArgumentException("Withdrawal must be positive");
}
if (amountInPaise > balanceInPaise) {
throw new IllegalStateException("Insufficient balance");
}
balanceInPaise -= amountInPaise;
}
public long balanceInPaise() {
return balanceInPaise;
}
public String owner() {
return owner;
}
}
package com.gocourse.bank;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
@Tag("fast")
@Timeout(value = 1, unit = TimeUnit.SECONDS)
@DisplayName("BankAccount")
class BankAccountTest {
private BankAccount account;
@BeforeEach
void openAccount() {
account = new BankAccount("Asha", 100_000); // ₹1,000.00
}
@Test
@DisplayName("cannot be opened with a negative balance")
void negativeOpeningBalance() {
assertThrows(IllegalArgumentException.class, () -> new BankAccount("Ravi", -1));
}
@Nested
@DisplayName("deposit")
class Deposit {
@Test
@DisplayName("adds the amount to the balance")
void addsAmount() {
account.deposit(25_050);
assertEquals(125_050, account.balanceInPaise());
}
@Test
@DisplayName("rejects zero")
void rejectsZero() {
assertThrows(IllegalArgumentException.class, () -> account.deposit(0));
}
}
@Nested
@DisplayName("withdraw")
class Withdraw {
@Test
@DisplayName("subtracts the amount from the balance")
void subtractsAmount() {
account.withdraw(40_000);
assertEquals(60_000, account.balanceInPaise());
}
@Test
@DisplayName("allows withdrawing the full balance")
void fullBalance() {
account.withdraw(100_000);
assertEquals(0, account.balanceInPaise());
}
@Test
@DisplayName("refuses to overdraw and keeps the balance unchanged")
void refusesOverdraft() {
IllegalStateException error =
assertThrows(IllegalStateException.class, () -> account.withdraw(100_001));
assertEquals("Insufficient balance", error.getMessage());
assertEquals(100_000, account.balanceInPaise());
}
}
@RepeatedTest(value = 3, name = "deposit then withdraw leaves balance unchanged ({currentRepetition}/{totalRepetitions})")
void depositThenWithdraw() {
account.deposit(999);
account.withdraw(999);
assertEquals(100_000, account.balanceInPaise());
}
}
Output in the Console Launcher:
└─ BankAccount ✔
├─ cannot be opened with a negative balance ✔
├─ depositThenWithdraw() ✔
│ ├─ deposit then withdraw leaves balance unchanged (1/3) ✔
│ ├─ deposit then withdraw leaves balance unchanged (2/3) ✔
│ └─ deposit then withdraw leaves balance unchanged (3/3) ✔
├─ deposit ✔
│ ├─ adds the amount to the balance ✔
│ └─ rejects zero ✔
└─ withdraw ✔
├─ subtracts the amount from the balance ✔
├─ allows withdrawing the full balance ✔
└─ refuses to overdraw and keeps the balance unchanged ✔
[ 9 tests successful ]
[ 0 tests failed ]
How it works:
- Class-level settings.
@Tag("fast")and@Timeout(1 s)on the class apply to every test method, including those in nested classes. - Fresh account per test.
@BeforeEachopens a new account with ₹1,000 before each test. Combined with a new test instance per method, no test can affect another, which is whyfullBalanceandsubtractsAmountboth start from 100,000 paise. - Grouped behaviour.
@Nestedclasses split deposit and withdraw rules, and the display names read like a specification of the account. - Edge cases.
fullBalancechecks the exact limit (withdrawing everything is allowed), andrefusesOverdraftchecks one paisa over the limit. It also confirms that a failed withdrawal leaves the balance unchanged. - Repeated round trip. The
@RepeatedTestruns a deposit-then-withdraw cycle three times as three separate tests, each with its own fresh account. - Money in paise. Storing amounts as
longpaise avoids the rounding problems ofdouble, soassertEqualscompares exact values.
The tree order in your report may differ, because JUnit does not promise a method order unless you use @TestMethodOrder.