Search code examples
javajunitassert

Assertion in Java JUnit Testing


I am new to java and I am learning about JUnit testing, All examples I find online are about adding two number.

This is my method on class SumOfAllSeries

 static int getIndex(int[] array) {

    int max = 0;

    for(int i= 0; i < array.length; i++) {

        if(array[i] > array[max]) {

            max = i;
        }   
    }

    return max;
}

This is what I tried to do on my JUnit and I cant seem to find it right, Please how can I test this code.I have an error: The method assertArrayEquals(int[], int[]) in the type Assert is not applicable for the arguments (int[], int) when I use AssertEquals it prints garbage and says expected is 4.

class SumOfAllSeriesTest {
    @Test
    void testGetIndex() {

        int array[] = {2,4,5,6,7};
        int calculateIndex = SumOfAllSeries.getIndex(array);

        assertEquals(4, calculateIndex);


    }

}

Update: I have tried to change array to 4 and used

assertEquals

Is this the correct way? I don't have anyone to ask and i want to understand this concept.


Solution

  • First note that getIndex() method doesn't compute a sum.
    It returns the index of the max value of the array.

    Whatever, to assert the index of the max value or the sum, you don't need to use assertArrayEquals() in your test.
    You don't want to assert arrays content but the index or the sum.
    So do instead :

    Assert.assertEquals(24, results); // for sum
    

    or

    Assert.assertEquals(4, results); // for index