Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using assertArrayEquals() with wildcards?

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]));
        }
    }
}
like image 494
Koraktor Avatar asked May 01 '26 20:05

Koraktor


1 Answers

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

like image 59
JB Nizet Avatar answered May 03 '26 10:05

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!