2

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.

6
  • Post a minimal reproducible example... Commented Jan 4, 2018 at 18:31
  • @Reimeus I have edited it please help me understand Junit Commented Jan 4, 2018 at 18:35
  • This has nothing to do with JUnit. The compiler error is pretty clear: the method expects two int[] as parameters, you give it an int[] and an int. What should it even mean for an int[] to be equal to an int? Commented Jan 4, 2018 at 18:36
  • @Turing85 thanks, i have updated the question, thanks for the explanation. Commented Jan 4, 2018 at 18:43
  • try to change the name of the variable result to calculatedIndex. Does that make more sense when reading? Commented Jan 4, 2018 at 18:53

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks very much, so with JUnit it is simply me writing what is expected of the code on my Assertions?
You are welcome. Sure. What the framework could do with the array to assert an int equality ? Providing in the assert invocation the expected and the actual is really all you need.
Thanks dude, It clicked now. Appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.