JUnit Assertions

Su Suriya Ravichandran Updated 18 Nov 2026
14 min read ·Lesson 251 of 306

JUnit assertions are the methods that decide whether a test passes or fails. Each one compares what your code actually did with what you expected, and if they differ, it throws an AssertionFailedError that stops the test and reports both values.

This lesson covers every assertion you will use in JUnit 6: assertEquals, assertTrue, assertNull, assertSame, the array and collection assertions, assertThrows, assertAll, assertTimeout, assertInstanceOf and fail. Each section shows a passing example and the exact failure message you get when it breaks. If you have not written a test yet, start with Java JUnit Basics, and see JUnit Test Methods for the annotations used around these assertions.


How JUnit Assertions Work

All assertions are static methods of the class org.junit.jupiter.api.Assertions. Most tests import them with a static import so you can write assertEquals(...) instead of Assertions.assertEquals(...).

import static org.junit.jupiter.api.Assertions.*;

When an assertion holds, nothing happens and the test continues. When it does not hold, JUnit throws an exception, the rest of the test method is skipped, and the test is reported as failed.

AssertionPasses when
assertEquals(expected, actual)expected.equals(actual) (or == for primitives)
assertNotEquals(unexpected, actual)The values are not equal
assertTrue(condition) / assertFalse(condition)The condition is true / false
assertNull(value) / assertNotNull(value)The value is / is not null
assertSame(expected, actual)Both refer to the same object (==)
assertArrayEquals(expected, actual)Arrays have equal elements in the same order
assertIterableEquals(expected, actual)Iterables have equal elements in the same order
assertThrows(type, executable)The code throws type or a subclass
assertDoesNotThrow(executable)The code throws nothing
assertAll(executables...)Every grouped assertion passes
assertTimeout(duration, executable)The code finishes within the duration
assertInstanceOf(type, value)The value is an instance of type
fail(message)Never: it always fails

Every assertion also accepts an optional message as its last argument, either a String or a Supplier<String>.


assertEquals and assertNotEquals

assertEquals is the assertion you will write most often. Always pass the expected value first and the actual value second, because JUnit uses that order in the failure message.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;

import org.junit.jupiter.api.Test;

class PriceCalculatorTest {

    int totalInRupees(int unitPrice, int quantity) {
        return unitPrice * quantity;
    }

    @Test
    void multipliesPriceByQuantity() {
        assertEquals(1497, totalInRupees(499, 3));
    }

    @Test
    void differentQuantitiesGiveDifferentTotals() {
        assertNotEquals(totalInRupees(499, 2), totalInRupees(499, 3));
    }

    @Test
    void showsAFailureMessage() {
        assertEquals(1500, totalInRupees(499, 3), "total for 3 books");
    }
}

Output for the third test:

org.opentest4j.AssertionFailedError: total for 3 books ==> expected: <1500> but was: <1497>

How it works:

  • The first two tests pass silently.
  • In the failing test, the message total for 3 books is printed before ==>, followed by the expected and actual values.
  • For objects, assertEquals calls equals(). Two String objects with the same text are equal even if they are different objects.

Comparing double and float Values With a Delta

Floating-point arithmetic is not exact. 0.1 + 0.2 is 0.30000000000000004, so comparing it with 0.3 fails. Pass a third argument, the delta, to allow a small difference.

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

import org.junit.jupiter.api.Test;

class DoubleAssertionTest {

    @Test
    void exactComparisonFails() {
        assertEquals(0.3, 0.1 + 0.2);
    }

    @Test
    void comparisonWithDeltaPasses() {
        assertEquals(0.3, 0.1 + 0.2, 0.000001);
    }
}

Output for the first test:

org.opentest4j.AssertionFailedError: expected: <0.3> but was: <0.30000000000000004>

How it works:

  • Without a delta, JUnit compares the two double values exactly, so the first test fails.
  • With a delta of 0.000001, the test passes because the difference is far smaller than that.

Note: For money, avoid double altogether. Use long paise or BigDecimal and compare exact values.


assertTrue and assertFalse

Use assertTrue and assertFalse for conditions that are naturally boolean, such as "the list is empty" or "the password is strong".

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;

class PasswordRulesTest {

    boolean isStrong(String password) {
        return password.length() >= 12
                && password.chars().anyMatch(Character::isDigit)
                && password.chars().anyMatch(Character::isUpperCase);
    }

    @Test
    void longPasswordWithDigitAndUppercaseIsStrong() {
        assertTrue(isStrong("GoCourse2026Java"));
    }

    @Test
    void shortPasswordIsWeak() {
        assertFalse(isStrong("Java1"), "passwords under 12 characters must be weak");
    }

    @Test
    void failingAssertTrue() {
        String password = "alllowercase1234";
        assertTrue(isStrong(password), () -> "expected strong password but got weak for: " + password);
    }
}

Output for the third test:

org.opentest4j.AssertionFailedError: expected strong password but got weak for: alllowercase1234 ==> expected: <true> but was: <false>

How it works:

  • assertTrue passes only when the condition is true; assertFalse only when it is false.
  • A plain assertTrue failure only says expected: <true> but was: <false>, which tells you very little. A message explains what was being checked.
  • The Supplier message () -> "..." + password is built only when the test fails, so it costs nothing for passing tests.

Note: Prefer assertEquals(3, list.size()) over assertTrue(list.size() == 3). The first prints the actual size when it fails; the second only prints false.


assertNull and assertNotNull

These check whether a method returned null, for example when a lookup finds nothing.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;

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

class CourseLookupTest {

    private final Map<String, String> coursesById = Map.of(
            "JAVA101", "Java Basics",
            "PY101", "Python Basics");

    String findTitle(String courseId) {
        return coursesById.get(courseId); // null when the id is unknown
    }

    @Test
    void knownIdReturnsTitle() {
        String title = findTitle("JAVA101");
        assertNotNull(title);
        assertEquals("Java Basics", title);
    }

    @Test
    void unknownIdReturnsNull() {
        assertNull(findTitle("GO999"));
    }
}

Output (mvn test, shortened):

[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

How it works:

  • assertNotNull runs first, so if title is null the test fails with a clear message instead of a NullPointerException later.
  • assertNull confirms the "not found" case. If it failed, JUnit would print expected: <null> but was: <...> with the unexpected value.

assertSame and assertNotSame

assertEquals checks that two objects are equal. assertSame checks that they are the same object in memory, using ==. This matters when testing caches and singletons.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;

import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;

class ConfigCacheTest {

    private final Map<String, StringBuilder> cache = new HashMap<>();

    StringBuilder loadConfig(String name) {
        return cache.computeIfAbsent(name, key -> new StringBuilder("config:" + key));
    }

    @Test
    void cacheReturnsTheSameObject() {
        StringBuilder first = loadConfig("app");
        StringBuilder second = loadConfig("app");
        assertSame(first, second);
    }

    @Test
    void equalTextButDifferentObjects() {
        String a = new String("gocourse");
        String b = new String("gocourse");
        assertEquals(a, b);    // same text
        assertNotSame(a, b);   // different objects
    }
}

Output (mvn test, shortened):

[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

How it works:

  • computeIfAbsent creates the StringBuilder once and returns the cached object on the second call, so assertSame passes.
  • new String(...) always creates a new object. The two strings are equal by equals() but are not the same object, so both assertions in the second test pass.

Assert Arrays and Collections

assertEquals on two arrays compares references, not contents, so it fails even for identical arrays. Use assertArrayEquals for arrays and assertIterableEquals for lists and other iterables.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;

import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;

class CollectionAssertionsTest {

    @Test
    void sortedArrayHasExpectedOrder() {
        int[] marks = {72, 45, 98, 60};
        Arrays.sort(marks);
        assertArrayEquals(new int[] {45, 60, 72, 98}, marks);
    }

    @Test
    void listsWithSameElementsAreEqual() {
        List<String> enrolled = List.of("Asha", "Ravi", "Meena");
        assertIterableEquals(List.of("Asha", "Ravi", "Meena"), enrolled);
        assertEquals(List.of("Asha", "Ravi", "Meena"), enrolled); // List.equals also works
    }

    @Test
    void arrayMismatchShowsTheIndex() {
        assertArrayEquals(new int[] {1, 2, 3}, new int[] {1, 2, 4});
    }
}

Output for the third test:

org.opentest4j.AssertionFailedError: array contents differ at index [2], expected: <3> but was: <4>

How it works:

  • assertArrayEquals compares element by element and reports the first index where the arrays differ.
  • For lists, assertEquals works too because List.equals compares contents. assertIterableEquals is useful when the two sides are different iterable types, and it also reports the differing index.
  • Order matters for both. To compare without order, convert both sides to a Set first.

For lines of text, such as log output, assertLinesMatch compares a list of expected lines where each line may also be a regular expression:

@Test
void logLinesMatch() {
    List<String> logLines = List.of("Server started on port 8080", "Loaded 42 courses");
    assertLinesMatch(List.of("Server started on port \\d+", "Loaded \\d+ courses"), logLines);
}

This test passes because each actual line either equals or matches the expected pattern. (Import assertLinesMatch from Assertions as well.)


Test Exceptions With assertThrows

assertThrows runs a lambda and passes only if it throws the expected exception type. It returns the exception, so you can also check its message.

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;

import org.junit.jupiter.api.Test;

class AgeValidatorTest {

    int parseAge(String input) {
        int age = Integer.parseInt(input.strip());
        if (age < 0 || age > 150) {
            throw new IllegalArgumentException("Age out of range: " + age);
        }
        return age;
    }

    @Test
    void negativeAgeIsRejected() {
        IllegalArgumentException error =
                assertThrows(IllegalArgumentException.class, () -> parseAge("-5"));
        assertEquals("Age out of range: -5", error.getMessage());
    }

    @Test
    void textInputThrowsNumberFormatException() {
        // NumberFormatException is a subclass of IllegalArgumentException
        assertThrows(IllegalArgumentException.class, () -> parseAge("twenty"));
        assertThrowsExactly(NumberFormatException.class, () -> parseAge("twenty"));
    }

    @Test
    void validAgeDoesNotThrow() {
        int age = assertDoesNotThrow(() -> parseAge(" 27 "));
        assertEquals(27, age);
    }

    @Test
    void failsWhenNothingIsThrown() {
        assertThrows(IllegalArgumentException.class, () -> parseAge("30"));
    }
}

Output for the fourth test:

org.opentest4j.AssertionFailedError: Expected java.lang.IllegalArgumentException to be thrown, but nothing was thrown.

How it works:

  • assertThrows accepts the given type or any subclass, so NumberFormatException satisfies IllegalArgumentException.class.
  • assertThrowsExactly accepts only that exact class, which is stricter.
  • assertDoesNotThrow returns the lambda's result, so you can check it in the next line.
  • If the lambda finishes normally, assertThrows fails with the message above.

Group Assertions With assertAll

Normally a test stops at the first failed assertion, so you only see one problem at a time. assertAll runs every assertion in the group and reports all failures together.

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;

class StudentProfileTest {

    record Student(String name, String email, int age, boolean active) {}

    Student loadStudent() {
        return new Student("asha", "asha@example.com", 21, false);
    }

    @Test
    void profileHasCorrectFields() {
        Student student = loadStudent();

        assertAll("student profile",
                () -> assertEquals("Asha", student.name(), "name"),
                () -> assertEquals("asha@example.com", student.email(), "email"),
                () -> assertEquals(21, student.age(), "age"),
                () -> assertTrue(student.active(), "active"));
    }
}

Output:

org.opentest4j.MultipleFailuresError: student profile (2 failures)
	org.opentest4j.AssertionFailedError: name ==> expected: <Asha> but was: <asha>
	org.opentest4j.AssertionFailedError: active ==> expected: <true> but was: <false>

How it works:

  • Each assertion is wrapped in a lambda, so assertAll can run them one after another and collect failures.
  • The report shows both problems at once: the name is lowercase and the student is inactive. Without assertAll, you would fix the name, rerun, and only then discover the second problem.
  • The heading student profile labels the group in the report.

Check Execution Time With assertTimeout

assertTimeout fails if a block of code takes longer than a given Duration. It is useful for code with a performance promise, such as a search that must answer quickly.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;

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

class SearchSpeedTest {

    String slowSearch(String keyword, long delayMillis) throws InterruptedException {
        Thread.sleep(delayMillis);
        return "Results for " + keyword;
    }

    @Test
    void fastSearchFinishesInTime() {
        String result = assertTimeout(Duration.ofMillis(500), () -> slowSearch("java", 50));
        assertEquals("Results for java", result);
    }

    @Test
    void slowSearchWaitsThenFails() {
        assertTimeout(Duration.ofMillis(100), () -> slowSearch("java", 400));
    }

    @Test
    void slowSearchIsAbortedEarly() {
        assertTimeoutPreemptively(Duration.ofMillis(100), () -> slowSearch("java", 5_000));
    }
}

Output for the second and third tests (numbers vary slightly):

org.opentest4j.AssertionFailedError: execution exceeded timeout of 100 ms by 302 ms
org.opentest4j.AssertionFailedError: execution timed out after 100 ms

How it works:

  • assertTimeout lets the code finish, then fails if it took too long. The second test waits the full 400 ms before reporting.
  • assertTimeoutPreemptively runs the code in a separate thread and stops waiting as soon as the limit is reached, so the third test fails after about 100 ms instead of 5 seconds.
  • Both return the block's result, as the first test shows.

Note: Because assertTimeoutPreemptively runs code in another thread, anything that relies on the current thread, such as ThreadLocal values or Spring transactions, may behave differently inside it. Use the plain assertTimeout when in doubt.


assertInstanceOf and fail

assertInstanceOf checks the runtime type of a value and returns it already cast, which saves a manual cast. fail fails a test unconditionally, which is useful in branches that should never be reached.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.fail;

import org.junit.jupiter.api.Test;

class PaymentTypeTest {

    sealed interface Payment permits CardPayment, UpiPayment {}
    record CardPayment(String lastFourDigits) implements Payment {}
    record UpiPayment(String upiId) implements Payment {}

    Payment parse(String input) {
        return input.contains("@") ? new UpiPayment(input) : new CardPayment(input.substring(input.length() - 4));
    }

    @Test
    void upiIdIsParsedAsUpiPayment() {
        UpiPayment upi = assertInstanceOf(UpiPayment.class, parse("asha@okbank"));
        assertEquals("asha@okbank", upi.upiId());
    }

    @Test
    void everyPaymentTypeIsHandled() {
        Payment payment = parse("4111111111111111");
        switch (payment) {
            case CardPayment card -> assertEquals("1111", card.lastFourDigits());
            case UpiPayment upi -> fail("A card number must not be parsed as UPI: " + upi);
        }
    }
}

Output (mvn test, shortened):

[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

How it works:

  • assertInstanceOf(UpiPayment.class, ...) passes and returns the value typed as UpiPayment, so upi.upiId() compiles without a cast.
  • If the type were wrong, it would fail with Unexpected type, expected: <...UpiPayment> but was: <...CardPayment>.
  • In the second test, the UpiPayment branch should never run for a card number. fail(...) makes the test fail with a clear message if it ever does.

Real-World Example: Testing a Shopping Cart With JUnit Assertions

This example tests a small shopping cart using most of the assertions from this lesson.

package com.gocourse.shop;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ShoppingCart {

    public record Item(String sku, String name, long priceInPaise, int quantity) {}

    private final List<Item> items = new ArrayList<>();
    private String couponCode;

    public void add(Item item) {
        if (item.quantity() <= 0) {
            throw new IllegalArgumentException("Quantity must be positive for " + item.sku());
        }
        items.add(item);
    }

    public void applyCoupon(String code) {
        if (!code.equals("GOCOURSE10")) {
            throw new IllegalStateException("Unknown coupon: " + code);
        }
        this.couponCode = code;
    }

    public long totalInPaise() {
        long subtotal = items.stream().mapToLong(i -> i.priceInPaise() * i.quantity()).sum();
        return couponCode == null ? subtotal : subtotal - subtotal / 10;
    }

    public List<Item> items() {
        return Collections.unmodifiableList(items);
    }

    public String couponCode() {
        return couponCode;
    }
}
package com.gocourse.shop;

import static org.junit.jupiter.api.Assertions.*;

import com.gocourse.shop.ShoppingCart.Item;
import java.util.List;
import org.junit.jupiter.api.Test;

class ShoppingCartTest {

    private final Item javaBook = new Item("BK-1", "Java Book", 49_900, 2);
    private final Item keyboard = new Item("KB-7", "Keyboard", 129_900, 1);

    @Test
    void newCartIsEmpty() {
        ShoppingCart cart = new ShoppingCart();
        assertAll("empty cart",
                () -> assertTrue(cart.items().isEmpty()),
                () -> assertEquals(0, cart.totalInPaise()),
                () -> assertNull(cart.couponCode()));
    }

    @Test
    void totalAddsPriceTimesQuantity() {
        ShoppingCart cart = new ShoppingCart();
        cart.add(javaBook);
        cart.add(keyboard);

        assertEquals(229_700, cart.totalInPaise(), "2 x 499.00 + 1 x 1299.00");
        assertIterableEquals(List.of(javaBook, keyboard), cart.items());
    }

    @Test
    void couponTakesTenPercentOff() {
        ShoppingCart cart = new ShoppingCart();
        cart.add(keyboard);
        cart.applyCoupon("GOCOURSE10");

        assertAll("discounted cart",
                () -> assertEquals("GOCOURSE10", cart.couponCode()),
                () -> assertEquals(116_910, cart.totalInPaise()));
    }

    @Test
    void invalidInputIsRejected() {
        ShoppingCart cart = new ShoppingCart();

        IllegalArgumentException badQuantity = assertThrows(IllegalArgumentException.class,
                () -> cart.add(new Item("BK-1", "Java Book", 49_900, 0)));
        assertEquals("Quantity must be positive for BK-1", badQuantity.getMessage());

        IllegalStateException badCoupon = assertThrows(IllegalStateException.class,
                () -> cart.applyCoupon("FREE100"));
        assertTrue(badCoupon.getMessage().contains("FREE100"));
    }

    @Test
    void itemsListCannotBeModifiedFromOutside() {
        ShoppingCart cart = new ShoppingCart();
        cart.add(javaBook);

        assertThrows(UnsupportedOperationException.class, () -> cart.items().clear());
        assertEquals(1, cart.items().size());
    }

    @Test
    void largeCartIsTotalledQuickly() {
        ShoppingCart cart = new ShoppingCart();
        for (int i = 0; i < 10_000; i++) {
            cart.add(new Item("SKU-" + i, "Item " + i, 100, 1));
        }
        long total = assertTimeout(java.time.Duration.ofMillis(200), cart::totalInPaise);
        assertEquals(1_000_000, total);
    }
}

Output of mvn test (shortened):

[INFO] Running com.gocourse.shop.ShoppingCartTest
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.061 s -- in com.gocourse.shop.ShoppingCartTest
[INFO] BUILD SUCCESS

How it works:

  1. Empty state. newCartIsEmpty uses assertAll so that, if several defaults were wrong, you would see all of them in one run.
  2. Exact money values. Prices are long paise, so assertEquals(229_700, ...) compares exact numbers with no delta. The message documents how the total was calculated.
  3. Order of items. assertIterableEquals confirms the cart keeps items in the order they were added.
  4. The discount rule. 1,299.00 minus 10 % is 1,169.10, which is 116_910 paise. Grouping it with the coupon check shows both the stored code and the total.
  5. Errors and messages. assertThrows returns each exception, so the test also checks that the messages name the bad SKU and the bad coupon.
  6. Encapsulation. Calling clear() on the returned list must throw UnsupportedOperationException, and the cart must still hold its item afterwards.
  7. Performance. assertTimeout returns the total, so the same line checks both speed and correctness.

The next lesson, JUnit Test Fixtures, shows how to remove the repeated new ShoppingCart() lines with @BeforeEach.

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 JUnit Assertions and get answers drawn from it.

Signed-in readers only.