Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test that a array contains elements with JUnit and AssertJ

I have followings Unit Test with JUnit 4.12 and AssertJ 3.11.0 and having interesting results. helloTest is green but worldTest is red.

@Test
public void helloTest() {
    Object[] array = new Object[2];
    String[] firstElement = new String[]{"Hello"};
    String[] secondElement = new String[]{"World"};
    array[0] = firstElement;
    array[1] = secondElement;
    assertThat(array).containsExactlyInAnyOrder(firstElement, secondElement);
}

@Test
public void worldTest() {
    Object[] array = new Object[1];
    String[] element = new String[]{"Hello"};
    array[0] = element;
    assertThat(array).containsExactlyInAnyOrder(element);
}

And the result from AssertJ is

 java.lang.AssertionError: 
 Expecting:
   <[["Hello"]]>
 to contain exactly in any order:
   <["Hello"]>
 elements not found:
   <["Hello"]>
 and elements not expected:
   <[["Hello"]]>

But why?

like image 218
Quang Nguyen Avatar asked Oct 29 '22 06:10

Quang Nguyen


1 Answers

It's a question of types. The following test will pass:

@Test
public void worldTest() {
    String[][] array = new String[1][];
    String[] element = new String[]{"Hello"};
    array[0] = element;
    assertThat(array).containsExactlyInAnyOrder(element);
}

Your worldTest fails because you are trying to assert that an object of type Object[] contains an element of type String[]. You are making this assertion using a method with this declaration:

ObjectArrayAssert<ELEMENT> containsExactlyInAnyOrder(ELEMENT... values)

This method expects the incoming type to match the type under inspection. In my example above this is true and hence the test passes. In your version of worldTest this is not true because one type is a String[] and the other type is an Object[].

like image 69
glytching Avatar answered Nov 15 '22 06:11

glytching