Maarten Dhondt Maarten Dhondt - 6 months ago 41
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 {}

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

Assertions.assertThat(list).containsOnlyOnce(B.class);
}

Answer

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() {
    @Override
    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();
list.add(b);
list.add(b);

Using the Java 8 Stream API it can be achieved like

long countOfClassB = list.stream().filter(t -> t instanceof B).count();
Assertions.assertThat(countOfClassB).isEqualTo(1L);
Comments