In Java application development with JUnit, there will be a certain case in which you need to verify that a method of a class won’t throw any exception when it is being tested. In other words, it requires to assert that no exception is thrown when the method gets executed.

With JUnit 5 or later, you can use the assertDoesNotThrow() method provided by the Assertions class for such purpose. The simplest form of this method takes an object of type Executable that defines execute() method, as shown in the below example:

@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:

 

Other JUnit Tutorials:


About the Author:

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.



Add comment