Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 297
Maarten Dhondt Avatar asked May 13 '16 09:05

Maarten Dhondt


Video Answer


2 Answers

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);
like image 179
Marcin Gołębski Avatar answered Oct 10 '22 16:10

Marcin Gołębski


I would use AssertJ extracting feature as is:

assertThat(list).extracting("class")
                .containsOnlyOnce(B.class);
like image 24
Joel Costigliola Avatar answered Oct 10 '22 16:10

Joel Costigliola