【发布时间】:2011-10-25 07:06:13
【问题描述】:
我想测试生成用于作为 UDP 数据包发送的字节数组的代码。
虽然我无法重现测试中的每个字节(例如随机字节、时间戳),但我想测试我可以预先确定的字节。
使用 JUnit 4.8(和 Mockito 1.8)是否可以实现以下操作?
Packet packet = new RandomPacket();
byte[] bytes = new byte[] {
0x00, 0x02, 0x05, 0x00, anyByte(), anyByte(), anyByte(), anyByte(), 0x00
};
assertArrayEquals(packet.getBytes(), bytes);
上面的示例当然不起作用,我只是在寻找一种在assertArrayEquals() 中使用某种通配符的方法。
PS:我现在唯一的选择是单独检查每个字节(并忽略随机字节)。但这很乏味,而且不能真正重复使用。
感谢 JB Nizet 的回答,我现在有了以下代码,工作正常:
private static int any() {
return -1;
}
private static void assertArrayEquals(int[] expected, byte[] actual) {
if(actual.length != expected.length) {
fail(String.format("Arrays differ in size: expected <%d> but was <%d>", expected.length, actual.length));
}
for(int i = 0; i < expected.length; i ++) {
if(expected[i] == -1) {
continue;
}
if((byte) expected[i] != actual[i]) {
fail(String.format("Arrays differ at element %d: expected <%d> but was <%d>", i, expected[i], actual[i]));
}
}
}
【问题讨论】:
标签: java junit bytearray mockito hamcrest