JUnit - Assert that no exception is thrown
- Details
- Written by Nam Ha Minh
- Last Updated on 09 July 2024   |   Print Email
@Test
public void testMethod() {
assertDoesNotThrow(new Executable() {
@Override
public void execute() throws Throwable {
classUnderTest.foo();
}
});
}As you can see, this test will pass if the foo() method of the class under test won’t throw any exception when it gets executed. Here, Executable is a functional interface declared in the org.junit.jupiter.api.function package. That means the above example can be rewritten with Lambda expression like this:@Test
public void testMethod() {
assertDoesNotThrow(() -> {
classUnderTest.foo();
});
}More precisely, the assertDoesNotThrow() method in JUnit 5 is used to ensure that that code block in the execute() method won’t throw any kind of exception - not just a single method call. Else the test will fail if the code block throws an exception.There’s an overload of this method, which allows you to pass a failure message if the test fails. For example:@Test
public void test() {
assertDoesNotThrow(() -> {
classUnderTest.foo();
}, "Failure message goes here");
}And in case you need to get a return value (result) if the assertion passes, use the assertDoesNotThrow(ThrowingSupplier) overload. Below is an example (given that the bar() method returns a String):String result = assertDoesNotThrow(new ThrowingSupplier<String>() {
@Override
public String get() throws Throwable {
return classUnderTest.bar();
}
});Here, ThrowingSupplier is a functional interface declared in the org.junit.jupiter.api.function package, which means the above example can be rewritten with Lambda expression as shown below:@Test
public void test() {
String result = assertDoesNotThrow(() -> {
return classUnderTest.bar();
});
}Those are some code examples showing you how to assert a piece of code or a method won’t throw any kind of exception. I hope you find this post helpful, and check for more with the links below. References:
- JUnit assertDoesNotThrow(Executable) Javadocs
- JUnit Executable interface
- JUnit assertDoesNotThrow(ThrowingSupplier) Javadocs
- JUnit ThrowingSupplier interface
Other JUnit Tutorials:
- JUnit Tutorial for beginner with Eclipse
- How to compile and run JUnit tests in command line
- JUnit Test Suite Example - How to create and run test suite in command line and Eclipse
- JUnit Test Exception Examples - How to assert an exception is thrown
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments