Java JUnit Test Methods

Su Suriya Ravichandran Updated 18 Nov 2026
13 min read ·Lesson 250 of 306

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:

RuleAllowedNot allowed
Visibilitypublic, protected, package-privateprivate
StaticInstance methodsstatic methods
Return typevoidAny other type (except for @TestFactory)
ParametersNone, or ones JUnit can supply such as TestInfoArbitrary 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. helperMethod has no annotation, so JUnit treats it as an ordinary method you can call from tests.
  • TestInfo is a built-in parameter type. JUnit fills it with details about the current test, such as its display name and tags.
  • A private, static or non-void method with @Test is 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 cart lists.
  • addTwoItems always 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 @BeforeEach method. 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:

  • ReplaceUnderscores turns trims_spaces_from_both_ends into trims spaces from both ends, and does the same for the class name.
  • An explicit @DisplayName always 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.
GeneratorExample result for adds_two_numbers()
Standard (default)adds_two_numbers()
Simpleadds_two_numbers (no parentheses when there are no parameters)
ReplaceUnderscoresadds two numbers
IndicativeSentencesCombines 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:

  • @Disabled skips 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, @EnabledIfEnvironmentVariable and @DisabledIfSystemProperty.
  • assumeTrue checks a condition inside the test. If it is false, JUnit aborts the test and reports it as skipped, not failed. On Linux, readsLinuxProcFile passes 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. loadsAllCourses is both slow and database.
  • Surefire's groups and excludedGroups options filter by tag. Gradle uses useJUnitPlatform { 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 @Test and runs the method five times, each as a separate test in the report.
  • The name pattern produces display names such as OTP check 3/5.
  • RepetitionInfo tells the method which repetition is running. The OTP generator is the one from Java SecureRandom, and %06d keeps 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 a TimeoutException.
  • The default unit is seconds, so @Timeout(5) means five seconds. Put @Timeout on 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 @Nested class must be a non-static inner class, so it can use the outer class's stack field.
  • For each test, JUnit runs the outer @BeforeEach first, then the inner one. Tests in AfterPushing therefore 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.OrderAnnotation sorts methods by their @Order value, lowest first, regardless of where they appear in the file.
  • Other orderers include MethodName (alphabetical), DisplayName and Random. Random is 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 @TestFactory method must return a Stream, Collection or Iterable of DynamicTest (or DynamicContainer). This is the one case where a test method is not void.
  • dynamicTest(name, executable) creates one test with a display name and the code to run.
  • Map.of has 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:

  1. Class-level settings. @Tag("fast") and @Timeout(1 s) on the class apply to every test method, including those in nested classes.
  2. Fresh account per test. @BeforeEach opens a new account with ₹1,000 before each test. Combined with a new test instance per method, no test can affect another, which is why fullBalance and subtractsAmount both start from 100,000 paise.
  3. Grouped behaviour. @Nested classes split deposit and withdraw rules, and the display names read like a specification of the account.
  4. Edge cases. fullBalance checks the exact limit (withdrawing everything is allowed), and refusesOverdraft checks one paisa over the limit. It also confirms that a failed withdrawal leaves the balance unchanged.
  5. Repeated round trip. The @RepeatedTest runs a deposit-then-withdraw cycle three times as three separate tests, each with its own fresh account.
  6. Money in paise. Storing amounts as long paise avoids the rounding problems of double, so assertEquals compares exact values.

The tree order in your report may differ, because JUnit does not promise a method order unless you use @TestMethodOrder.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java JUnit Test Methods and get answers drawn from it.

Signed-in readers only.