Skip to content

Instantly share code, notes, and snippets.

@pablohdzvizcarra
Created March 22, 2025 14:06
Show Gist options
  • Save pablohdzvizcarra/6282e2ec2a0c17d84ad2b99cddadf45b to your computer and use it in GitHub Desktop.
Save pablohdzvizcarra/6282e2ec2a0c17d84ad2b99cddadf45b to your computer and use it in GitHub Desktop.
How to test if a test does not throws an exception in Java
package com.github.pablohdzvizcarra.lesson28;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class MethodValidatorTest {
@Test
void givenValidProduct_whenValidateGetterMethods_thenDoesNotThrowException() {
MethodValidator productTest = new MethodValidator();
try {
productTest.testGetters(Product.class);
assertTrue(true, "Method executed without exceptions");
} catch (Exception e) {
fail("Method throws an unspected exception: " + e.getMessage());
}
}
@Test
void givenValidDataClass_whenValidateSetterMethods_thenDoesNotThorwException() {
MethodValidator methodValidator = new MethodValidator();
try {
methodValidator.testSetters(Product.class);
assertTrue(true, "Method executed without exceptions");
} catch (Exception e) {
fail("Method throws an unspected exception: " + e.getMessage());
}
}
@Test
void givenInvalidDataClass_whenValidateSetterMethods_thenThrowsException() {
MethodValidator methodValidator = new MethodValidator();
assertThrows(IllegalStateException.class, () -> {
methodValidator.testSetters(WrongProductDataClass.class);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment