Assert Exception in JUnit 5 and JUnit 4

In JUnit 5, we can utilize the assertThrows assertion to test for expected exceptions. This assertion method not only provides the thrown exception but also allows us to verify the exception message.

JUnit Assert Exception can be paraphrased as “Exception thrown by JUnit Assert.”

I will provide you with one paraphrased option:
This is an uncomplicated illustration that demonstrates how to confirm an exception in JUnit 5.

String str = null;
assertThrows(NullPointerException.class, () -> str.length());

JUnit 5 provides a method to assert exception messages.

Suppose we define a class as:

class Foo {
	void foo() throws Exception {
		throw new Exception("Exception Message");
	}
}

We should explore how to test an exception and its accompanying message.

Foo foo = new Foo();
Exception exception = assertThrows(Exception.class, () -> foo.foo());
assertEquals("Exception Message", exception.getMessage());

Referred to as JUnit 4’s Expected Exception.

We have the option to define the expected exception thrown by the test method by utilizing the expected attribute of the JUnit 4 @Test annotation.

@Test(expected = Exception.class)
public void test() throws Exception {
	Foo foo = new Foo();
	foo.foo();
}

JUnit 4’s Assert Exception Message

In order to test the exception message, we must utilize the ExpectedException rule. The following example provides a comprehensive demonstration on how to test both the exception and its message.

 com.scdev.junit4;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class JUnit4TestException {

	@Rule
	public ExpectedException thrown = ExpectedException.none();

	@Test
	public void test1() throws Exception {
		Foo foo = new Foo();
		thrown.expect(Exception.class);
		thrown.expectMessage("Exception Message");
		foo.foo();
	}
}

That’s all for a brief summary on testing anticipated exceptions in both JUnit 5 and JUnit 4.

You can find additional examples of JUnit 5 in our project’s GitHub Repository.

 

More tutorials

Primefaces’ Message, Messages, and Growl components(Opens in a new browser tab)

A native guide to the atop command in Linux(Opens in a new browser tab)

The program in Java for displaying “Hello World”(Opens in a new browser tab)

Converting a Python string to an integer and vice versa.(Opens in a new browser tab)

The Python functions ord() and chr()(Opens in a new browser tab)

Leave a Reply 0

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