Search code examples
javajunit4junit5

Parameterized Junit class - How to send an ArrayList as a parameter to a method()


Consider the below code:

import static org.junit.Assert.assertEquals;
import java.util.Collection;
import java.util.List;
import org.assertj.core.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public class StackFrustratedCoderTest {
    private List<Integer> input;
    private Integer expected;
    private ItcStackFrustrated itcStack;

    public StackFrustratedCoderTest(List<Integer> array, Integer expected){
        this.input = array;
        this.expected = expected;
    }

    @Before
    public void init(){
        itcStack = new ItcStackFrustrated();
    }

    @Parameterized.Parameters
    public Collection parameterInput(){
        return Arrays.asList(new Object[][] {{1,7,2,2,4,4}, 11}});
    }

    @Test
    public void testFrustatedCoder(){
        assertEquals(this.expected, itcStack.check(this.input));
    }
}

Consider the method itcStack.check() is a function to be tested and as an argument, it needs ArrayList variable.

How to code it in the below method:

@Parameterized.Parameters
        public Collection parameterInput(){
            return Arrays.asList(new Object[][] {{1,7,2,2,4,4}, 11}});
        } 

The above code shows compilation error. {1,7,2,2,4,4} is an int array but I need ArrayList. Any suggestions are appreciated.

And also, if any article can be provided where its explained how do the Parameterized class functions internally.


Solution

  • This here:

    {1,7,2,2,4,4}
    

    is a literal that would create an array of int.

    Simply go:

    Arrays.asList(1, 7, 2, ...);
    

    instead.

    EDIT

    We can do that in this way.

    int[] array = new int[]{1,7,2,2,4,4};
    return Arrays.asList(new Object[][] {{Arrays.asList(array), 11}});