Created
April 12, 2022 12:32
-
-
Save hertzsprung/47b92c348c785519ee922c04f2f2f02e to your computer and use it in GitHub Desktop.
AssertJ exception handling alternatives
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.jupiter.api.Test; | |
import static org.assertj.core.api.Assertions.assertThat; | |
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; | |
import static org.assertj.core.api.Assertions.assertThatThrownBy; | |
import static org.assertj.core.api.Assertions.catchThrowableOfType; | |
import static org.assertj.core.api.InstanceOfAssertFactories.type; | |
public class AssertJExceptionsTest { | |
private final Properties properties = new Properties(); | |
private final String field = "bar"; | |
@Test | |
void test1() throws Exception { | |
try { | |
properties.afterPropertiesSet(); | |
} catch (ValidationException ex) { | |
assertThat(ex.getField()).endsWith(field); | |
} | |
} | |
@Test | |
void test2() { | |
ValidationException ex = catchThrowableOfType(properties::afterPropertiesSet, ValidationException.class); | |
assertThat(ex).isNotNull(); | |
assertThat(ex.getField()).endsWith(field); | |
} | |
@Test | |
void test3() { | |
assertThatExceptionOfType(ValidationException.class).isThrownBy(properties::afterPropertiesSet) | |
.satisfies((ex) -> assertThat(ex.getField()).endsWith(field)); | |
} | |
@Test | |
void test4() { | |
assertThatThrownBy(properties::afterPropertiesSet).isInstanceOf(ValidationException.class) | |
.satisfies((ex) -> assertThat(((ValidationException) ex).getField()).endsWith(field)); | |
} | |
@Test | |
void test5() { | |
assertThatThrownBy(properties::afterPropertiesSet) | |
.isInstanceOfSatisfying(ValidationException.class, (ex) -> assertThat(ex.getField()).endsWith(field)); | |
} | |
@Test | |
void test6() { | |
assertThatThrownBy(properties::afterPropertiesSet) | |
.asInstanceOf(type(ValidationException.class)) | |
.satisfies((ex) -> assertThat(ex.getField()).endsWith(field)); | |
} | |
} | |
class Properties { | |
public void afterPropertiesSet() throws Exception { | |
throw new ValidationException(); | |
} | |
} | |
class ValidationException extends Exception { | |
public String getField() { | |
return "foo"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment