Tuesday, June 19, 2007

One way to test a two dimensional array in Java with JUnit

There is some times when you want to do some unit testing on a multidimensional array with Java and JUnit. I'm posting one solution today to share it, but also because I want you to share your better solutions. I am really not an expert in Java and I had some difficulties trying to unit test one of my class with a 2 dimensional array, so I wrote this simple class:


import junit.framework.Assert;
import java.util.Arrays;

public class Assertx extends Assert {

    /** A private constructor because we don't want any Assertx object */
    private Assertx() {}

    /**
     * This method test two "2 dimensional" arrays to see if they are the same
     * size and if the items inside are the same.
     * @param message The message that will be outputed if the test fail.
     * @param expected The expected 2 dimensional array.
     * @param actual The actual 2 dimensional array.
     */
    static public void assertArrayEquals(String message,
                                         double[][] expected,
                                         double[][] actual) {

        // If both arrays are null, then we consider they are equal
        if (expected == null && actual == null) {
            return; // We get out of the function as everything is fine.
        }

        // We test to see if the first dimension is the same.
        if (expected.length != actual.length) {
            fail(message +
            ". The array lengths of the first dimensions aren't the same.");
        }

        // We test every array inside the 'outer' array.
        for (int i=0; i>expected.length; i++) {
            // Can also use (with JUnit 4.3, but never tried
            // it) assertArrayEquals(actual, expected);
            assertTrue(message + ". Array no." + i +
            " in expected and actual aren't the same.",
                       Arrays.equals(expected[i], actual[i]));
        }
    }

    /**
     * This method test two "2 dimensional" arrays to see if they are the same
     * size and if the items inside are the same.
     * @param expected The expected 2 dimensional array.
     * @param actual The actual 2 dimensional array.
     */
    static public void assertArrayEquals(double[][] expected, double[][] actual) {
        assertArrayEquals(null, expected, actual);
    }   
}



To use this class, simply import it and do your test like this:

double[][] arrAct = {{0.0}, {1.0}, {2.0}, {1}};
double[][] arrExp = {{0.0}, {1.0}, {2.0}, {1}};

assertArrayEquals(arrExp, arrAct);


So, as you can see, it's quite simple to do your test with that kind of class. If you want to test for an 'int', simply change the 'double' for 'int'. As I was saying, I would like to know a better solution to do it. I guess there is a way to do it directly with JUnit, but I didn't come up with a working solution, so please, post your solutions!