java - JUnit - 测试数组结果
问题描述
如何使用 Junit 单元测试比较数组以确保预期值与实际值相同@Test
这是我到目前为止所拥有的:
@前
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));
}
解决方案
您可以使用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"]>
推荐阅读
- composer-php - 精确版本的 TYPO3 的作曲家设置
- firebase - 如何编写firestore规则来查询另一个集合,其中值等于某个值
- javascript - 使用一行中的数据在 ag-grid (Vue.js) 中创建自定义聚合函数
- openapi - OpenAPI 中正则表达式“模式”的共同点是什么?
- java - Spring Boot 属性解析不正确
- c++ - Check for end-of-list in boost::intrusive::list without container?
- javascript - 如何抓取网页内容需要点击按钮
- c# - ASP.NET 3.5 使用 System.Drawing.Printing PrintDocument 打印现有 PDF 文件
- python - 如何在 Django 中使用 __init__ 预填充模型表单字段中的值?
- c# - 通过 join 将 c# linq 转换为 sql 代码并进行优化