Stefan Berger
Stefan Berger

Reputation: 315

Is there a type parameter matcher in hamcrest?

I want to test a method like this

public List<String> giveStrings();

Using hamcrest I can test for the returned type, for example

assertThat(giveStrings(), instanceOf(ArrayList.class));

But what I want to know is whether it's a List of Strings. Is there an existing matcher for that?

Thanks in advance

Upvotes: 1

Views: 516

Answers (1)

John B
John B

Reputation: 32949

So simple answer is No because at runtime Java does type-erasure so all generics are converted to Object. So at runtime your List<String> is actually just a List or List<Object>. The String type information is lost.

Consider using

IsIterableContainingInOrder.containsInOrder(
               CoreMatchers.instanceOf(String.class),
               ...)

Per comment, use Every

assertThat(myList, Every.everyItem(instanceOf(String.class));

Upvotes: 2

Related Questions