Could I somehow use AssertJ to assert a List has only one instance of a (sub)class?
public class A {}
public class B extends A {}
public class C extends A {}
@Test
public void test() {
List<A> list = new ArrayList<A>();
list.add(new B());
Assertions.assertThat(list).containsOnlyOnce(B.class);
}
There is a method hasOnlyElementsOfType(Class), which verifies that all elements in the Iterable have the specified type (including subclasses of the given type).
The solution could look like:
assertThat(list).hasOnlyElementsOfType(B.class).hasSize(1);
I would use AssertJ extracting feature as is:
assertThat(list).extracting("class")
.containsOnlyOnce(B.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With