JUnit参数化测试 - 多维数组混合类型

时间:2016-04-01 13:51:43

标签: java arrays multidimensional-array junit mixed

我遇到了使用JUnit 4.x参数化的问题。我的参数化测试由1个数组混合类型{{integer multidimensional array}和1 double}作为参数组成,我很难知道如何声明它们。请参阅下面的代码。

测试机器人的类

public class Robot {
    public static double companyBotStrategy(int[][] trainingData) {
        double botTime = 0;
        double isCorrect = 0;

        for (int i = 0; i < trainingData.length; i++) {
            int[] v = trainingData[i];
            if (v[1] == 1) {
                botTime += v[0];
                isCorrect++;
            }
        }
        return botTime / isCorrect;

    }

}

JUnit测试参数化

import static org.junit.Assert.assertEquals;

import java.util.Arrays;

import org.junit.Test;
import org.junit.runners.Parameterized.Parameters;

public class RobotPrmtTest {

    private double expected;
    private int[][] trainingData;

    public RobotPrmtTest(int[][] trainingData, double expected) {
        this.trainingData = trainingData;
        this.expected = expected;
    }

    @Parameters(name = "{index}")
    public static Iterable<Object[]> getLoadTest() {

        return Arrays.asList(new Object[][] { });
        /*loadTest array mix type
         * {int [][] trainingData, double expected}
         * looks like it
        {
            {
                {{ 6, 1 }, { 4, 1 }},4.5
            },
            {
                {{4,1},{4,-1}, {0,0}, {6,1}},5.0
            }
        }
        */
    }

    @Test
    public void validateParamaters() {
        assertEquals("divergente", expected, Robot.companyBotStrategy(trainingData));
    }

}

1 个答案:

答案 0 :(得分:1)

@Parameters(name = "{index}")
public static Iterable<Object[]> getLoadTest() {

    return Arrays.asList(new Object[][] {
        {
            new int[][]{{6, 1}, {4, 1}}, 4.5
        },
        {
            new int[][]{{4, 1}, {4, -1}, {0, 0}, {6, 1}}, 5.0
        }

    });
}

旁注:您必须在断言方法中提供delta:

double delta = 0.1; // choose something appropriate here
assertEquals("divergente", expected, Robot.companyBotStrategy(trainingData), delta);