Maarten Dhondt Maarten Dhondt - 8 months ago 55
Java Question

Assert List contains only one instance of a class using AssertJ

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 {}

public void test() {
List<A> list = new ArrayList<A>();
list.add(new B());



You need to define a Condition.

Following will assert that list contains only a single object reference of type B.class.

Condition condition = new Condition() {
    public boolean matches(Object o) {
        return o.getClass() == B.class;

Assertions.assertThat(list).areExactly(1, condition);

It will fail for following cases:

list.add(new B());
list.add(new B());

and also for

B b = new B();

Using the Java 8 Stream API it can be achieved like

long countOfClassB = -> t instanceof B).count();