Search code examples
javajunitjunit4

Returning something other than null


This is probably a really bad way of writing code but heres a program that calculates the total of each row and print it all in brackets.

public static int[] rowsSums(int[][] array) {
    int[][] numArray = {

                            {3, -1,  4,  0},
                            {5,  9, -2,  6},
                            {5,  3,  7, -8}

                       };
    int rowTotal = 0;
    int row2Total = 0;
    int row3Total = 0;
    for (int i = 0; i < numArray[0].length; i++) {
        rowTotal += numArray[0][i];
        row2Total += numArray[1][i]; 
        row3Total += numArray[2][i];
    }

    System.out.println("(" + rowTotal + "," + row2Total + "," + row3Total + ")");
    return null;

}

The output without JUnit is:

(6,18,7)

I am in the process of testing this with JUnit and my code for this:

@Test
public void rowsSums() {

    int [] i = new int [] {6, 18, 7};
    assertEquals(i, Exercise2.rowsSums(numArray));
}

Yes, I know my output is not supposed to be null because JUnit hates it. What other variable can I return without making JUnit fail or spit an error?

I have to keep these as it is

public static int[] rowsSums(int[][] array) {

int[][] numArray = {

UPDATE: No matter what I try, JUnit always comes up with this error PrntScrn of Error


Solution

  • To return the int[] containing the sums, you'd do

    return new int[] { rowTotal, row2Total, row3Total };
    

    That's something you can assert as well then

    assertArrayEquals(i, Exercise2.rowsSums(numArray));
    

    Note that it is good practice to separate calculation and output, ie you should move the System.out.println to another function accepting the returned array as a parameter.