How to use a bytearray

I wrote very basic test for Octets on valid ip adresses. but i seem to use the byte array wrong since they failed on a correct implementation.
My idea was to put an uri with ipv4 adress and build my own bytearray with the correct values so i can just compare the two arrays.

but even the contents of the array confuse me. for example i tested the input “scheme://”
then i filled a bytearray with the values 1-4 in this order. the contents of these two arrays according to the testresults were not only unexpected but also different:

returned wrong byte array expected:<[B@305a7827> but was:<[B@3e9d805c>

my interpretation for them is not 1 2 3 4 at all. So how do i use the byte array the correct way?

I interpret your question that you check equality on arrays?
There are three one-line ways:

(  I) a==b
( II) a.equals(b)
(III) Arrays.equals(a,b)

(I) and (II) are the same and unsuited for your use case.
Both compare if they are the same array (as in exactly the same object) and not equal arrays.
In C-speak one would say that (I) and (II) compare the pointer of the array whereas (III) compares the content.

You probably want to use (III).

I wanted to use assertEquals since this function works on strings. Do the Junit assertions only work on int, bool and strings or are there more options?

assertEquals uses the a.equals(b) method:

For strings, this is okay as you learned in the lecture. (String overwrites the equals method)
For arrays like byte[] this falls back to Object.equals as arrays to not overwrite this method.

The documentation also tells you that this usage is

Deprecated. use assertArrayEquals

The array method uses the correct equality Arrays.deepEquals.

Alternatively, you could implement your own comparison to make sure.

You should use separate assertion methods for separate use cases (strings vs arrays).

1 Like