📘 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.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Overview
In this post, we will learn all the Assert statements available in JUnit 4.The assertions are available for all primitive types, Objects, and arrays (either of primitives or Objects).
2. JUnit 4 Assertions with Examples
2.1 assertEquals
@Test
public void whenAssertingEquality_thenEqual() {
String expected = "Ramesh";
String actual = "Ramesh";
assertEquals(expected, actual);
}
assertEquals("failure - strings are not equal", expected, actual);
2.2 assertArrayEquals
@Test
public void whenAssertingArraysEquality_thenEqual() {
char[] expected = {'J','u','n','i','t'};
char[] actual = "Junit".toCharArray();
assertArrayEquals(expected, actual);
}
@Test
public void givenNullArrays_whenAssertingArraysEquality_thenEqual() {
int[] expected = null;
int[] actual = null;
assertArrayEquals(expected, actual);
}
2.3 assertNotNull and assertNull
@Test
public void whenAssertingNull_thenTrue() {
Object car = null;
assertNull("The car should be null", car);
}
2.4 assertNotSame and assertSame
@Test
public void whenAssertingNotSameObject_thenDifferent() {
Object cat = new Object();
Object dog = new Object();
assertNotSame(cat, dog);
}
2.5 assertTrue and assertFalse
@Test
public void whenAssertingConditions_thenVerified() {
assertTrue("5 is greater then 4", 5 > 4);
assertFalse("5 is not greater then 6", 5 > 6);
}
2.6 fail
@Test
public void whenCheckingExceptionMessage_thenEqual() {
try {
methodThatShouldThrowException();
fail("Exception not thrown");
} catch (UnsupportedOperationException e) {
assertEquals("Operation Not Supported", e.getMessage());
}
}
2.7 assertThat
@Test
public void testAssertThatHasItems() {
assertThat(
Arrays.asList("Java", "Kotlin", "Scala"),
hasItems("Java", "Kotlin"));
}
3. Conclusion
In this post, we have learned JUnit 4 assertions with examples. The assertions are available for all primitive types, Objects, and arrays (either of primitives or Objects).Read more on JUnit 4 Developers Guide.
Comments
Post a Comment
Leave Comment