BAEL-7783: Assert properties of custom exceptions with catchThrowableOfType in AssertJ (#16442)

This commit is contained in:
Azhwani 2024-04-27 11:56:24 +02:00 committed by GitHub
parent 267bd54092
commit 54aee18a7f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 60 additions and 1 deletions

View File

@ -0,0 +1,22 @@
package com.baeldung.assertj.exceptions;
public class CityNotFoundException extends RuntimeException {
private String city;
private String message;
CityNotFoundException(String city, String message) {
this.city = city;
this.message = message;
}
public String getCity() {
return city;
}
@Override
public String getMessage() {
return message;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.assertj.exceptions;
import java.util.Arrays;
import java.util.List;
public final class CityUtils {
private static final List<String> CITIES = Arrays.asList("Tamassint", "London", "Madrid", "New york");
public static String search(String searchedCity) {
return CITIES.stream()
.filter(searchedCity::equals)
.findFirst()
.orElseThrow(() -> new CityNotFoundException(searchedCity, "The specified city is not found"));
}
}

View File

@ -1,13 +1,15 @@
package com.baeldung.assertj.exceptions; package com.baeldung.assertj.exceptions;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import org.junit.Test; import org.junit.Test;
public class Java8StyleAssertions { public class Java8StyleAssertions {
@ -63,4 +65,22 @@ public class Java8StyleAssertions {
.hasMessageContaining("/ by zero"); .hasMessageContaining("/ by zero");
} }
@Test
public void whenUsingCatchThrowableOfType_thenAssertField() {
String givenCity = "Paris";
CityNotFoundException exception = catchThrowableOfType(() -> CityUtils.search(givenCity), CityNotFoundException.class);
assertThat(exception.getCity()).isEqualTo(givenCity);
assertThat(exception.getMessage()).isEqualTo("The specified city is not found");
}
@Test
public void whenUsingAssertThatThrownBy_thenAssertField() {
String givenCity = "Geneva";
assertThatThrownBy(() -> CityUtils.search(givenCity)).isInstanceOf(CityNotFoundException.class)
.extracting("city")
.isEqualTo(givenCity);
}
} }