Domanda

I want to test code that produces byte arrays used to send as UDP packets.

Although I'm not able to reproduce every byte in my test (e.g. random bytes, timestamps), I'd like to test the bytes that I can predetermine.

Is something like the following possible using JUnit 4.8 (and Mockito 1.8)?

Packet packet = new RandomPacket();

byte[] bytes = new byte[] {
    0x00, 0x02, 0x05, 0x00, anyByte(), anyByte(), anyByte(), anyByte(), 0x00
};

assertArrayEquals(packet.getBytes(), bytes);

The sample above is of course not working, I'm just searching for a way to use some sort of wildcard in assertArrayEquals().

PS: My only alternative right now is to check each byte individually (and omit random ones). But this is quiet tedious and not really reusable.


Thanks to the answer from JB Nizet I have the following code in place now, working just fine:

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]));
        }
    }
}
È stato utile?

Soluzione

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).

Altri suggerimenti

If you are going to be writing a lot of code like this, I would write a separate class to "decode" the packet into meaningful fields. Then (of course, after testing that the class itself works) you can write sensible tests like

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

etc.

That way, you are not "omitting random bytes", and your code will be much more readable (if a tad more verbose).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top