Passing arrays to Parameterized JUnit

落爺英雄遲暮 提交于 2019-12-05 14:07:26

The reason why it is failing is because your test expects Integer arrays whereas you are passing Object type. So you are expanding the type. Try this:

@Parameterized.Parameters
    public static Collection testCases() {
        return Arrays.asList(new Integer[][][] {
            {{1,1,1}, {2,2,2}, {3,3,3}},
            {{2,2,2}, {3,3,3}, {4,4,4}}
        });
    }

This solution uses junitparams, implements junitparams.converters.Converter and parses list of long values as parameters.

package example;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Arrays;
import java.util.stream.Collectors;

import org.junit.Test;
import org.junit.runner.RunWith;

import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import junitparams.converters.ConversionFailedException;
import junitparams.converters.Converter;
import junitparams.converters.Param;

@RunWith(JUnitParamsRunner.class)
public class LongArrayParameterTest {

    @Parameters({ "0|10", "1|10;20;30" })
    @Test
    public void test(final long otherParameter, @LongArrayParam final long[] expected) {
        System.out.println(Arrays.stream(expected).boxed().map(l -> Long.toString(l)).collect(Collectors.toList()));
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.PARAMETER)
    @Param(converter = LongArrayConverter.class)
    public @interface LongArrayParam {

    }

    public static class LongArrayConverter implements Converter<LongArrayParam, long[]> {

        @Override
        public void initialize(final LongArrayParam annotation) {
        }

        @Override
        public long[] convert(final Object param) throws ConversionFailedException {
            final String str = (String) param;
            final String[] longStrings = str.split(";");
            return Arrays.stream(longStrings).mapToLong(s -> Long.parseLong(s)).toArray();
        }

    }
}

This parser does not support empty list.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!