3

我想测试生成用于作为 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]));
        }
    }
}
4

2 回答 2

2

You could simply write your expected array as an array of integers, and use a special value (such as -1) to represent the wildcard. It's the same trick as the read methods of the input streams. You would just have to write your custom assertEqualsWithWildCard(int[] expected, byte[] actual).

于 2011-10-25T07:25:02.847 回答
1

如果您要编写大量这样的代码,我会编写一个单独的类来将数据包“解码”为有意义的字段。然后(当然,在测试类本身有效之后)你可以编写明智的测试,比如

assertEquals(42, packet.length());
assertEquals(0xDEADBEEF, packet.checksum());

等等

这样,您就不会“省略随机字节”,并且您的代码将更具可读性(如果更冗长的话)。

于 2011-10-25T07:22:05.393 回答