Search code examples
javajunitparameterized

Varargs error when using Parameterized class in JUnit


I am creating a test case using the Parameterized class to improve scalability. I have something like the following...

@RunWith(Parameterized.class)
public class Test
{
    private final translator;

    @Parameterized.Parameters(name = "translate {0}")
    public static Collection parameters()
    {
        return Arrays.asList(new Object[][] {
                { Translate.EN },
                { Translate.FR }
        });
    }

    public Test1(Translate translate)
    {
        this.translator = new TranslatorImpl(translate);
    ...
    ...

I have a Linter that is throwing an error for the following part...

return Arrays.asList(new Object[][] {
        { Translate.EN },
        { Translate.FR }
});

It says...

There's no point in creating an array solely for the purpose of passing it as a varargs (...) argument; varargs is an array. Simply pass the elements directly. They will be consolidated into an array automatically. Incidentally passing an array where Object ... is expected makes the intent ambiguous: Is the array supposed to be one object or a collection of objects?

I might have to add more arguments, and so using the Parameterized class is helpful and I would like to use that, but I am not sure how to resolve the issue that I'm getting and if it is even worth resolving. Any ideas would be helpful.


Solution

  • Arrays.asList's signature is public static <T> List<T> asList(T... a) So instead of feeding an array to Arrays.asList, you can feed it individual array elements. In this particular case:

    return Arrays.asList(
      new Translate[] { Translate.EN },
      new Translate[] { Translate.FR }
    );