【问题标题】:JUnit - Test array results [duplicate]JUnit - 测试数组结果[重复]
【发布时间】:2019-02-19 09:53:46
【问题描述】:

如何使用 @Test 中的 Junit 单元测试比较数组以确保预期值与实际值相同

这是我目前所拥有的:

@之前

public void initialize() throws Exception{
    bob = new Student(18, "Bob Maher", new String []{"COSC 222","COSC 311", "MATH 200", "MATH 220"});
    bill = new Student(19, "Bill Cosby", new String []{"COSC 222", "COSC 404", "ENGL 112"});
    ben = new Student(24, "Ben Mckenny", new String []{"COSC 222", "COSC 111", "MATH 200", "PHYS 101"});
}

@Test

public void testGetClasses() throws Exception {
    //TODO: test that the classes array returned is correct
    ArrayList<Student> list = new ArrayList<>(Arrays.asList(bob, bill, ben));

    ArrayList<Student> results = Arrays.asList(bob,bill.ben))

    assertTrue(list.containsAll(results) && results.containsAll(list));
}

【问题讨论】:

  • 你关心元素的顺序吗?
  • assertArrayEquals(expectedArray, actualArray); 将完成这项工作。如果长度和单个值相同,则返回 true

标签: java junit


【解决方案1】:

您可以使用AssertJ,也可以使用containsExactly()containsExactlyInAnyOrder()。例如:

String[] expected = { "ABC", "123" };
String[] actual = { "ABC", "234" };
assertThat(actual).containsExactly(expected);

会产生错误:

java.lang.AssertionError: 
Expecting:
  <["ABC", "234"]>
to contain exactly (and in same order):
  <["ABC", "123"]>
but some elements were not found:
  <["123"]>
and others were not expected:
  <["234"]>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 2014-01-09
    • 1970-01-01
    • 2016-11-04
    相关资源
    最近更新 更多