Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hamcrest Matchers - Assert Type of List

The Problem

I'm currently trying to use Hamcrest Matchers to assert that the list type being returned is of a specific type. For example, let's say I have the following List that is being returned by my service call:

List<SomePOJO> myList;

I want to assert that the list being returned is parametrized of type SomePOJO and not TheOtherPOJO. However, it appears that Hamcrest Matchers does not have this sort of functionality.

What I Have Tried

After some research, I have seen the following options:

  1. I have seen that there is hasItem(isA(SomePJO.class)), however this only works if there is an element in the list, and not if the list is empty.
  2. I could use is(instanceOf(List.class)), however this will only assert that the item being returned is a List; it does not assert what type of list is being returned.
  3. I can also add an element to the list immediately before the assert statement and then using assertThat(somePojo.get(0), is(instanceOf(SomePOJO.class))), however this isn't very clean. It is also very similar to point #1.

Conclusion / The Question

Using Hamcrest Matchers, is there a way to assert that an empty list is parametrized of a certain type (such as assertThat(myList, is(aListOf(SomePOJO.class))))?

like image 815
Mike Koch Avatar asked May 29 '14 14:05

Mike Koch


People also ask

What are Hamcrest assertions?

Hamcrest is used for unit testing in Java. The goal of Hamcrest is to make it easier to read and write test cases. We use Hamcrest to write the matcher objects that allow us to define the match rules declarative.

What is org Hamcrest matchers in?

Hamcrest is the well-known framework used for unit testing in the Java ecosystem. It's bundled in JUnit and simply put, it uses existing predicates – called matcher classes – for making assertions.

Why are there Hamcrest matchers?

Purpose of the Hamcrest matcher framework. Hamcrest is a widely used framework for unit testing in the Java world. Hamcrest target is to make your tests easier to write and read. For this, it provides additional matcher classes which can be used in test for example written with JUnit.

Which of the following is used to check whether all the elements are present in a given list collection in strict order?

To check tha collection contains items in expected (given) order you can use Hamcrest's containsInRelativeOrder method.


1 Answers

You can't. This is due to type erasure, you're not able to inspect the generic type. The compiler will enforce this for you. If you really want to test this, one option would be to grab the first element and make sure you can cast it to SomePOJO. (or alternatively grab every element and attempt the cast, but I believe this is overkill).

like image 136
Chris Thompson Avatar answered Sep 27 '22 22:09

Chris Thompson