Added better exception for null collection elements; fixes gh-703

This commit is contained in:
Marcin Grzejszczak
2018-08-08 18:09:27 +02:00
parent 6d1cb05a77
commit e5b0a9dabc
2 changed files with 26 additions and 1 deletions

View File

@@ -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

View File

@@ -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<>();