* @param fieldName name of the field being filled
* @param list List, which items should be checked
* @return Type-checked List
- * @throws IllegalArgumentException if a list item is not instance of {@code requiredItemClass}
+ * @throws IllegalArgumentException if a list item is not instance of {@code requiredClass}
* @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
*/
@SuppressWarnings("unchecked")
try {
collection.forEach(item -> requiredClass.cast(requireNonNull(item)));
} catch (ClassCastException | NullPointerException e) {
- throw new IllegalArgumentException("Invalid input list item for property \"" + requireNonNull(fieldName)
+ throw new IllegalArgumentException("Invalid input item for property \"" + requireNonNull(fieldName)
+ "\"", e);
}
}
import java.util.Collections;
import java.util.List;
+import java.util.Set;
import org.junit.Test;
public class CodeHelpersTest {
() -> CodeHelpers.checkListFieldCast(CodeHelpersTest.class, "foo", List.of(new Object())));
assertThat(iae.getCause(), instanceOf(ClassCastException.class));
}
+
+ @Test
+ public void testCheckSetFieldCast() {
+ assertNull(CodeHelpers.checkSetFieldCast(CodeHelpersTest.class, "foo", null));
+ assertSame(Set.of(), CodeHelpers.checkSetFieldCast(CodeHelpersTest.class, "foo", Set.of()));
+ final var list = Set.of(this);
+ assertSame(list, CodeHelpers.checkSetFieldCast(CodeHelpersTest.class, "foo", list));
+
+ IllegalArgumentException iae = assertThrows(IllegalArgumentException.class,
+ () -> CodeHelpers.checkSetFieldCast(CodeHelpersTest.class, "foo", Collections.singleton(null)));
+ assertThat(iae.getCause(), instanceOf(NullPointerException.class));
+
+ iae = assertThrows(IllegalArgumentException.class,
+ () -> CodeHelpers.checkSetFieldCast(CodeHelpersTest.class, "foo", Set.of(new Object())));
+ assertThat(iae.getCause(), instanceOf(ClassCastException.class));
+ }
}