Search code examples
javajunitmultidimensional-array

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?


Solution

  • Answers:

    1. Yes, the static variable will return the instance of the completed table, assuming that at the end of setTable() you set the completed table to the table variable. If you don't then it will not have the correct instance.

      However, from a design standpoint, it would be better to have an accessor method, such as getTable() for the completed table if you are setting it to a variable in MyClass, but that is a different issue.

    2. To test that the 2D array is created, I would suggest creating an array that represents each row of the 2D array, example

      char[] row0 == test.table[0]
      char[] row1 == test.table[1].
      

      You would need to create these Arrays yourself filled with the values you would expect to be in the table created from setTable(). Then you can have use assertArrayEquals() for each row. Example:

      public class SetTableTest{
      
          @Test
          public void test(){
              MyClass test = new MyClass();
              test.setTable(2, 2, 5);
              char[] row0 = {x, x} // This is whatever you would expect to be in row 0
              char[] row1 = {x, x} // This is whatever you would expect to be in row 1
              assertArrayEquals(row0, test.table[0]);
              assertArrayEquals(row1, test.table[1]);
          }
      }