比较 JUnit 断言中的数组,简洁的内置方式?
是否有一种简洁的内置方法可以对 JUnit 中的两个类似类型的数组进行 equals 断言?默认情况下(至少在 JUnit 4 中)它似乎对数组对象本身进行实例比较。
EG,不起作用:
int[] expectedResult = new int[] { 116800, 116800 };
int[] result = new GraphixMask().sortedAreas(rectangles);
assertEquals(expectedResult, result);
当然,我可以手动完成:
assertEquals(expectedResult.length, result.length);
for (int i = 0; i < expectedResult.length; i++)
assertEquals("mismatch at " + i, expectedResult[i], result[i]);
..但是有更好的方法吗?
Is there a concise, built-in way to do equals assertions on two like-typed arrays in JUnit? By default (at least in JUnit 4) it seems to do an instance compare on the array object itself.
EG, doesn't work:
int[] expectedResult = new int[] { 116800, 116800 };
int[] result = new GraphixMask().sortedAreas(rectangles);
assertEquals(expectedResult, result);
Of course, I can do it manually with:
assertEquals(expectedResult.length, result.length);
for (int i = 0; i < expectedResult.length; i++)
assertEquals("mismatch at " + i, expectedResult[i], result[i]);
..but is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
使用 org.junit.Assert 的方法
assertArrayEquals:
如果此方法不可用,您可能不小心从
junit.framework
导入了Assert类。Use org.junit.Assert's method
assertArrayEquals
:If this method is not available, you may have accidentally imported the Assert class from
junit.framework
.您可以使用 Arrays.equals(..) :
You can use
Arrays.equals(..)
:我更喜欢将数组转换为字符串:
这样我可以清楚地看到错误值在哪里。这仅适用于小型数组,但我在单元测试中很少使用项目数超过 7 的数组。
当
toString
重载返回所有基本信息时,此方法适用于基本类型和其他类型。I prefer to convert arrays to strings:
this way I can see clearly where wrong values are. This works effectively only for small sized arrays, but I rarely use arrays with more items than 7 in my unit tests.
This method works for primitive types and for other types when overload of
toString
returns all essential information.Assert.assertArrayEquals("message", ExpectedResult, result)
Assert.assertArrayEquals("message", expectedResult, result)
JUnit 5 我们可以导入 Assertions 并使用 Assertions.assertArrayEquals 方法
JUnit 5 we can just import Assertions and use Assertions.assertArrayEquals method
使用 junit4 和 Hamcrest 您可以获得比较数组的简洁方法。它还提供了故障跟踪中错误所在位置的详细信息。
故障跟踪输出:
Using junit4 and Hamcrest you get a concise method of comparing arrays. It also gives details of where the error is in the failure trace.
Failure Trace output:
我知道问题是针对 JUnit4 的,但如果您碰巧被 JUnit3 困住了,您可以创建一个简短的实用函数,如下所示:
在 JUnit3 中,这比直接比较数组更好,因为它将准确地详细说明哪些元素不同。
I know the question is for JUnit4, but if you happen to be stuck at JUnit3, you could create a short utility function like that:
In JUnit3, this is better than directly comparing the arrays, since it will detail exactly which elements are different.
org.junit.jupiter 中的类断言.api
使用:
Class Assertions in org.junit.jupiter.api
Use: