BAEL-7783: Assert properties of custom exceptions with catchThrowableOfType in AssertJ (#16442)
This commit is contained in:
parent
267bd54092
commit
54aee18a7f
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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"));
|
||||
}
|
||||
|
||||
}
|
|
@ -1,13 +1,15 @@
|
|||
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.assertThatExceptionOfType;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
import static org.assertj.core.api.Assertions.catchThrowableOfType;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class Java8StyleAssertions {
|
||||
|
@ -63,4 +65,22 @@ public class Java8StyleAssertions {
|
|||
.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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue