简体   繁体   English

使用 JUnit 和 AssertJ 测试数组是否包含元素

[英]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.我使用 JUnit 4.12 和 AssertJ 3.11.0 进行了以下单元测试,并获得了有趣的结果。 helloTest is green but worldTest is red . helloTestgreenworldTestred

@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 AssertJ 的结果是

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

But why?但为什么?

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[] .您的worldTest失败,因为您试图断言Object[]类型的Object[]包含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[] .在您的worldTest版本中,这是不正确的,因为一种类型是String[]而另一种类型是Object[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM