JUnit Assertions

Filed Under: JUnit

JUnit Assertions allows us to write effective test methods. JUnit 5 is the latest version and JUnit Jupiter provides a lot of assertions to assert different types of statements.

JUnit Assertions

JUnit Jupiter org.junit.jupiter.api.Assertions class provides a collection of utility methods to use in our test code. All these methods are static, so we can import them and write fluent code. Almost all of these methods are overloaded to support primitives, objects, Collections, Stream, Arrays etc.


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

Let’s look at some of the important JUnit assert methods with an example.

fail()

This is used to fail a test, it’s useful when your test method is work in progress and you want to indicate that by fail-fast your test. There are many overloaded fail() methods, let’s look at some of them.


@Test
@DisplayName("This will Fail, don't worry!")
void test_fail() {
	fail();
	fail("Not yet implemented");
	fail(() -> {
		return "Not yet implemented";
	});
	fail("Not Yet Implemented", new RuntimeException("Explicitly Failed"));
	fail(new RuntimeException("Explicitly Failed"));

}

We can provide custom failure message and specify the cause of failure.

assertNull() and assertNotNull()

These methods are used to check if the specified object is null or not. We can also specify custom failure message.


@Test
@DisplayName("assertNull Examples")
void test_assertNull() {
	assertNull(null);
	//assertNull(new Object(), "assertNull Fail Message");
}

@Test
@DisplayName("assertNotNull Examples")
void test_assertNotNull() {
	assertNotNull(new Object());
	//assertNotNull(null, "assertNotNull Fail Message");
}

assertSame() and assertNotSame()

These methods are used to assert that expected and actual elements are same or not. JUnit uses == operator for these methods to check if they are referring to same object or not.


@Test
@DisplayName("assertSame Examples")
void test_assertSame() {
	assertSame("Hi", "Hi");
	// this will fail
	// assertSame("Hi", new String("Hi"), "My Failure Message");

}

@Test
@DisplayName("assertNotSame Examples")
void test_assertNotSame() {
	assertNotSame("Hi", "Hello");
	// this will fail
	//assertNotSame("Hi", "Hi", "assertNotSame Failure Message");

}

assertTrue() and assertFalse()

Asserts that the supplied condition is true or false.


@Test
@DisplayName("assertTrue Examples")
void test_assertTrue() {
	assertTrue(3 > 0);
	assertTrue(() -> {
		return true;
	});

	assertTrue(3 > 0, "assertTrue fail message");
	assertTrue(3 > 0, () -> {
		return "assertTrue fail message";
	});

	assertTrue(() -> {
		return true;
	}, "assertTrue fail message");
	assertTrue(() -> {
		return true;
	}, () -> {
		return "assertTrue fail message";
	});
}

@Test
@DisplayName("assertFalse Examples")
void test_assertFalse() {
	assertFalse(3 < 0);
	assertFalse(() -> {
		return false;
	});

	assertFalse(3 < 0, "assertFalse fail message");
	assertFalse(3 < 0, () -> {
		return "assertFalse fail message";
	});

	assertFalse(() -> {
		return false;
	}, "assertFalse fail message");
	assertFalse(() -> {
		return false;
	}, () -> {
		return "assertFalse fail message";
	});
}

assertEquals() and assertNotEquals()

These two methods are used to assert that expected and actual objects are equal or not. They use equals() method of the object to check equality.


@Test
@DisplayName("assertEquals Examples")
void test_assertEquals() {
	assertEquals(10, 10);
	assertEquals(true, true, "assertEquals Failure Message");
	assertEquals("Hi", new String("Hi"));
	assertEquals(new File("test"), new File("test"));
}

@Test
@DisplayName("assertNotEquals Examples")
void test_assertNotEquals() {
	assertNotEquals(10, 100);
	assertNotEquals(true, false, "assertEquals Failure Message");
	assertNotEquals("Hi", new String("Hello"));
	assertNotEquals(new File("test"), new File("test1"));
}

assertArrayEquals()

Asserts that expected and actual arrays are deeply equal. The arrays elements are matched index by index.


@Test
@DisplayName("assertArrayEquals Examples")
void test_assertArrayEquals() {
	String[] s1 = { "A", "B" };
	String[] s2 = { "A", "B" };
	assertArrayEquals(s1, s2);
	assertArrayEquals(s1, s2, "My Custom Failure Message");
}

assertIterableEquals()

This method is used for iterables to check if they are equal or not. Note that the underlying implementation can be different. The elements are matched index by index for equality.


@Test
@DisplayName("assertIterableEquals Examples")
void test_assertIterableEquals() {
	List<String> l1 = new ArrayList<>(Arrays.asList("A", "B"));
	List<String> l2 = new LinkedList<>(Arrays.asList("A", "B"));
	assertIterableEquals(l1, l2);
	assertIterableEquals(l1, l2, "Custom Failure Message");
}

assertThrows()

Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.

If no exception is thrown, or if an exception of a different type is thrown, this method will fail.

This method follows inheritance hierarchy, so the assert will pass if the expected type is Exception and actual is RuntimeException.


@Test
@DisplayName("assertThrows Examples")
void test_assertThrows() {
	assertThrows(RuntimeException.class, () -> {
		throw new RuntimeException();
	});
	assertThrows(Exception.class, () -> {
		throw new RuntimeException();
	});

	// this will fail
	// assertThrows(IOException.class, () -> {throw new RuntimeException();});

	// assertThrows(IOException.class, () -> {throw new RuntimeException();}, "assertThrows Failure Message");
}

assertDoesNotThrow()

Asserts that execution of the supplied executable does not throw any kind of exception. This method takes org.junit.jupiter.api.function.Executable instance as argument. Executable is a functional interface that can be used to implement any generic block of code that potentially throws a Throwable.


class MyExecutable implements Executable {

	@Override
	public void execute() throws Throwable {
		System.out.println("Hello There!");
	}

}

We can use lambda expressions to create Executable if we are not planning to reuse it.


@Test
@DisplayName("assertDoesNotThrow Examples")
void test_assertDoesNotThrow() {
	assertDoesNotThrow(new MyExecutable());
	assertDoesNotThrow(new MyExecutable(), "assertDoesNotThrow custom message");
}

assertAll()

Asserts that all supplied executables do not throw exceptions. We can pass Array, Stream or a Collection of Executable objects.


@Test
@DisplayName("assertAll Examples")
void test_assertAll() {
	assertAll(Arrays.asList(new MyExecutable()));
	assertAll(new MyExecutable());
	assertAll(Stream.of(new MyExecutable()));
	//assertAll("My Executables Heading Error Message", () -> {throw new Exception("Hi");});
}

assertTimeout()

Asserts that execution of the supplied executable completes before the given timeout is exceeded.

The executable will be executed in the same thread as that of the calling code. Consequently, execution of the executable will not be preemptively aborted if the timeout is exceeded.


@Test
@DisplayName("assertTimeout Examples")
void test_assertTimeout() {
	assertTimeout(Duration.ofSeconds(1), new MyExecutable());
	assertTimeout(Duration.ofSeconds(3), () -> {
		Thread.sleep(2000);
		System.out.println("Done");
	});
	// this will fail
	/*
	assertTimeout(Duration.ofNanos(1), () -> {
		Thread.sleep(20);
		System.out.println("Done");
	}, "assertTimeout Failure Message: Too less time to execute");
	*/
}

assertTimeoutPreemptively()

Asserts that execution of the supplied executable completes before the given timeout is exceeded.

The executable will be executed in a different thread than that of the calling code. Furthermore, execution of the executable will be preemptively aborted if the timeout is exceeded.


@Test
@DisplayName("assertTimeoutPreemptively Examples")
void test_assertTimeoutPreemptively() {
	assertTimeoutPreemptively(Duration.ofSeconds(1), new MyExecutable());
	assertTimeoutPreemptively(Duration.ofMillis(100), () -> System.out.println("Hello There"));
	// this will timeout for sure
	// assertTimeoutPreemptively(Duration.ofNanos(1), () -> System.out.println("Hello There"));

	/*
	assertTimeoutPreemptively(Duration.ofSeconds(1), () -> {
		throw new RuntimeException("");
	});
	*/
	assertTimeoutPreemptively(Duration.ofSeconds(1), new MyExecutable(),
			"MyExecutable didn't completed within 1 second");
	assertTimeoutPreemptively(Duration.ofSeconds(1), new MyExecutable(), () -> {
		return "MyExecutable didn't completed within 1 second";
	});
	/*
	assertTimeoutPreemptively(Duration.ofSeconds(2), () -> {
		throw new RuntimeException("");
	}, "MyExecutable didn't completed within 2 second");
	*/
}

JUnit Assert Examples Test

Below image shows the JUnit test results view in Eclipse when the test class was executed.

JUnit Assertions, junit assert example

Summary

JUnit Jupiter provides a lot of assertions to help us write fluent test code. It’s always a good idea to import these assertion static methods and then write clean code.

You can checkout complete code from our GitHub Repository.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages