Tools and Technologies Used
- Eclipse photon (only this eclipse version supports JUnit 5)
- Maven
- JUnit 5
- JDK 8 or later
assertThrows Methods
- static T assertThrows(Class expectedType, Executable executable) - Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.
- static T assertThrows (Class expectedType, Executable executable, String message) - Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.
- static T assertThrows (Class expectedType, Executable executable, Supplier messageSupplier) - Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.
assertThrows Method Example
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class AssertThrowsExample {
@Test
void exceptionTesting() {
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("a message");
});
assertEquals("a message", exception.getMessage());
}
}
Output
Reference
Related JUnit 5 Examples
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment