Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit Testing void 2D array

I'm just starting out with testing.

The method I'm trying to test has no return value (void), but it creates a static 2D array (char[][]) in its own class, so from what I understand, that is its side effect.

Here is some mock code:

public class MyClass{

    public static char[][] table;

    public void setTable(int rows, int columns, int number){
        board = new char[n][m];
        // more code that alters the table in a specific way, 
        // depending on the 3rd parameter
    }

Now for the testing, I was thinking of doing something like:

public class SetTableTest{

    @Test
    public void test(){
        MyClass test = new MyClass();
        assertArrayEquals(**********, test.table);
    }
}

I have 2 questions:

  1. Am I allowed comparing to a static variable like I did (test.table) ie. will that actually return an "instance" of the completed table?

  2. I'm fairly certain that there's no assertArrayEquals equivalent for 2D arrays, so how do I go about this?

like image 684
Tiberiu Avatar asked Aug 23 '26 08:08

Tiberiu


1 Answers

The answer is already given, but for the sake of other users I am going to add another approach.

To compare two arrays, double[][] arr1, arr2, one may use Arrays.deepequals(arr1, arr2) which returns true or false. The signature of this fucntion is:

java.util.Arrays.deepEquals(Object[] a1, Object[] a2)

For a unit test a single line would then suffice:

assertTrue(Arrays.deepEquals(arr1, arr2));
like image 50
Azim Avatar answered Aug 25 '26 21:08

Azim



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!