Added better exception for null collection elements; fixes gh-703
This commit is contained in:
@@ -30,14 +30,21 @@ public class CollectionAssert<ELEMENT> extends IterableAssert<ELEMENT> {
|
||||
isNotNull();
|
||||
isNotEmpty();
|
||||
for (Object anActual : this.actual) {
|
||||
if (anActual == null) {
|
||||
failWithMessageRelatedToRegex(regex, anActual);
|
||||
}
|
||||
String value = anActual.toString();
|
||||
if (!value.matches(regex)) {
|
||||
failWithMessage("The value <%s> doesn't match the regex <%s>", value, regex);
|
||||
failWithMessageRelatedToRegex(regex, value);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
private void failWithMessageRelatedToRegex(String regex, Object value) {
|
||||
failWithMessage("The value <%s> doesn't match the regex <%s>", value, regex);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flattens the collection and checks whether size is greater than or equal to the provided value
|
||||
* @param size - the flattened collection should have size greater than or equal to this value
|
||||
|
||||
@@ -33,6 +33,18 @@ public class CollectionAssertTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_throw_an_exception_when_element_is_null() {
|
||||
Collection collection = collectionWithNulls();
|
||||
|
||||
try {
|
||||
SpringCloudContractAssertions.assertThat(collection).allElementsMatch("[0-9]");
|
||||
Assertions.fail("should throw exception");
|
||||
} catch (AssertionError e) {
|
||||
Assertions.assertThat(e).hasMessageContaining("The value <null> doesn't match the regex <[0-9]>");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_throw_an_exception_when_collection_is_null() {
|
||||
Collection collection = null;
|
||||
@@ -265,6 +277,12 @@ public class CollectionAssertTests {
|
||||
return list;
|
||||
}
|
||||
|
||||
private Collection<String> collectionWithNulls() {
|
||||
List<String> list = new ArrayList<>();
|
||||
list.add(null);
|
||||
return list;
|
||||
}
|
||||
|
||||
private Collection nestedCollection() {
|
||||
List list = new ArrayList<>();
|
||||
List list1 = new ArrayList<>();
|
||||
|
||||
Reference in New Issue
Block a user