fest asserting order in list

648 Views Asked by At

I would like to test if the elements in a list are in a particular order. Specifically I would like to test for a member of the elements. So something like:

assertThat(listOfObjects).hasProperty(name).inOrder("one", "two", "three");

Is is possible to do something like this ? Right now I manually iterate over the elements and have an assertion for each one.

1

There are 1 best solutions below

3
Dan Temple On

Having a quick browse though the version 1 source code (link here) I found this method which claims to be doing what you want:

/**
 * Verifies that the actual {@code List} contains the given objects, in the same order. This method works just like
 * {@code isEqualTo(List)}, with the difference that internally the given array is converted to a {@code List}.
 *
 * @param objects the objects to look for.
 * @return this assertion object.
 * @throws AssertionError       if the actual {@code List} is {@code null}.
 * @throws NullPointerException if the given array is {@code null}.
 * @throws AssertionError       if the actual {@code List} does not contain the given objects.
 */
public @Nonnull ListAssert containsExactly(@Nonnull Object... objects) {
  checkNotNull(objects);
  return isNotNull().isEqualTo(newArrayList(objects));
}

If I'm understanding the Javadoc correctly, you would just do this:

assertThat(listOfObjects).containsExactly(object1, object2, object3);

Note though that there were some issues with this method in version 2.0-M8. As detailed here! They were resolved in version 2.0-M9.