📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Overview
JUnit Jupiter comes with many of the assertion methods that JUnit 4 has and adds a few that lend themselves well to being used with Java 8 lambdas.
JUnit 5 Assertions with Examples
assertArrayEquals
@Test
public void whenAssertingArraysEquality_thenEqual() {
char[] expected = { 'J', 'u', 'p', 'i', 't', 'e', 'r' };
char[] actual = "Jupiter".toCharArray();
assertArrayEquals(expected, actual, "Arrays should be equal");
}
assertEquals
@Test
public void whenAssertingEquality_thenEqual() {
float square = 2 * 2;
float rectangle = 2 * 2;
assertEquals(square, rectangle);
}
@Test
public void whenAssertingEqualityWithDelta_thenEqual() {
float square = 2 * 2;
float rectangle = 3 * 2;
float delta = 2;
assertEquals(square, rectangle, delta);
}
assertTrue and assertFalse
@Test
public void whenAssertingConditions_thenVerified() {
assertTrue(5 > 4, "5 is greater the 4");
assertTrue(null == null, "null is equal to null");
}
@Test
public void givenBooleanSupplier_whenAssertingCondition_thenVerified() {
BooleanSupplier condition = () -> 5 > 6;
assertFalse(condition, "5 is not greater then 6");
}
assertNull and assertNotNull
@Test
public void whenAssertingNotNull_thenTrue() {
Object dog = new Object();
assertNotNull(dog, () -> "The dog should not be null");
}
@Test
public void whenAssertingNull_thenTrue() {
Object cat = null;
assertNull(cat, () -> "The cat should be null");
}
assertSame and assertNotSame
@Test
public void whenAssertingSameObject_thenSuccessfull() {
String language = "Java";
Optional<String> optional = Optional.of(language);
assertSame(language, optional.get());
}
fail
@Test
public void whenFailingATest_thenFailed() {
// Test not completed
fail("FAIL - test not completed");
}
assertAll
@Test
public void givenMultipleAssertion_whenAssertingAll_thenOK() {
assertAll(
"heading",
() -> assertEquals(4, 2 * 2, "4 is 2 times 2"),
() -> assertEquals("java", "JAVA".toLowerCase()),
() -> assertEquals(null, null, "null is equal to null")
);
}
assertIterableEquals
@Test
public void givenTwoLists_whenAssertingIterables_thenEquals() {
Iterable<String> al = new ArrayList<>(asList("Java", "Junit", "Test"));
Iterable<String> ll = new LinkedList<>(asList("Java", "Junit", "Test"));
assertIterableEquals(al, ll);
}
assertLinesMatch
@Test
public void whenAssertingEqualityListOfStrings_thenEqual() {
List<String> expected = asList("Java", "\\d+", "JUnit");
List<String> actual = asList("Java", "11", "JUnit");
assertLinesMatch(expected, actual);
}
assertNotEquals
@Test
public void whenAssertingEquality_thenNotEqual() {
Integer value = 5; // result of an algorithm
assertNotEquals(0, value, "The result cannot be 0");
}
assertThrows
@Test
void whenAssertingException_thenThrown() {
Throwable exception = assertThrows(
IllegalArgumentException.class,
() -> {
throw new IllegalArgumentException("Exception message");
}
);
assertEquals("Exception message", exception.getMessage());
}
assertTimeout and assertTimeoutPreemptively
@Test
public void whenAssertingTimeout_thenNotExceeded() {
assertTimeout(
ofSeconds(2),
() -> {
// code that requires less then 2 minutes to execute
Thread.sleep(1000);
}
);
}
Complete example for reference
import static java.time.Duration.ofMillis;
import static java.time.Duration.ofMinutes;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class AssertionsDemo {
@Test
void standardAssertions() {
assertEquals(2, 2);
assertEquals(4, 4, "The optional assertion message is now the last parameter.");
assertTrue('a' < 'b', () -> "Assertion messages can be lazily evaluated -- "
+ "to avoid constructing complex messages unnecessarily.");
}
@Test
void groupedAssertions() {
// In a grouped assertion all assertions are executed, and any
// failures will be reported together.
assertAll("person",
() -> assertEquals("John", person.getFirstName()),
() -> assertEquals("Doe", person.getLastName())
);
}
@Test
void dependentAssertions() {
// Within a code block, if an assertion fails the
// subsequent code in the same block will be skipped.
assertAll("properties",
() -> {
String firstName = person.getFirstName();
assertNotNull(firstName);
// Executed only if the previous assertion is valid.
assertAll("first name",
() -> assertTrue(firstName.startsWith("J")),
() -> assertTrue(firstName.endsWith("n"))
);
},
() -> {
// Grouped assertion, so processed independently
// of results of first name assertions.
String lastName = person.getLastName();
assertNotNull(lastName);
// Executed only if the previous assertion is valid.
assertAll("last name",
() -> assertTrue(lastName.startsWith("D")),
() -> assertTrue(lastName.endsWith("e"))
);
}
);
}
@Test
void exceptionTesting() {
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("a message");
});
assertEquals("a message", exception.getMessage());
}
@Test
void timeoutNotExceeded() {
// The following assertion succeeds.
assertTimeout(ofMinutes(2), () -> {
// Perform task that takes less than 2 minutes.
});
}
@Test
void timeoutNotExceededWithResult() {
// The following assertion succeeds, and returns the supplied object.
String actualResult = assertTimeout(ofMinutes(2), () -> {
return "a result";
});
assertEquals("a result", actualResult);
}
@Test
void timeoutNotExceededWithMethod() {
// The following assertion invokes a method reference and returns an object.
String actualGreeting = assertTimeout(ofMinutes(2), AssertionsDemo::greeting);
assertEquals("Hello, World!", actualGreeting);
}
@Test
void timeoutExceeded() {
// The following assertion fails with an error message similar to:
// execution exceeded timeout of 10 ms by 91 ms
assertTimeout(ofMillis(10), () -> {
// Simulate task that takes more than 10 ms.
Thread.sleep(100);
});
}
@Test
void timeoutExceededWithPreemptiveTermination() {
// The following assertion fails with an error message similar to:
// execution timed out after 10 ms
assertTimeoutPreemptively(ofMillis(10), () -> {
// Simulate task that takes more than 10 ms.
Thread.sleep(100);
});
}
private static String greeting() {
return "Hello, World!";
}
}
Conclusion
org.junit.jupiter.api.Assertions
class.JUnit 5 Related Posts
- Overview of JUnit 5
- JUnit 5 Maven Example
- JUnit 5 Standard Test Class Basic Template
- JUnit 5 Annotations with Examples
- JUnit 5 Assertions with Examples
- JUnit 5 Nested Tests Example
- JUnit 5 Disabling Tests Examples
- JUnit 5 Display Names Example
- JUnit 5 Repeated Tests with Examples
- JUnit 5 Exception Testing with Example
Comments
Post a Comment
Leave Comment