简体   繁体   中英

Expected values for Parameterized Junit test case for finding Max number in an array

Parameterized junit test can be written to test for multiple values. In this case what should be in the expected value? I'm storing the values to be tested as list, and the elements in the list are the candidates for the test data.

 @RunWith(Parameterized.class)
public class MaxInArrayTest {

    @Parameter
    public int[] a1;

    @Parameters
    public static Collection<int[]> data(){
        int[][] data = new int[][]{{1,2,3,4},{20,30,40,50}};
        return Arrays.asList(data);
    }

    @Test
    public void testMaxInArray(){
        MaxInArray maxInArray = new MaxInArray();
        Assert.assertEquals(maxInArray.findMax(a1), maxInArray.findMax(a1));
    }
}

Although this works, to calculate expected value, it is calling the same method. I want to store the expected values and then check them against the actual values. How does it need to be done?

The parameters need to contain the inputs, but also the expected output:

@RunWith(Parameterized.class)
public class MaxInArrayTest {

    private static class ArrayAndExpectedMax {
        private int[] array;
        private int expectedMax;

        public ArrayAndExpectedMax(int[] array, int expectedMax) {
            this.array = array;
            this.expectedMax = expectedMax;
        }

        public int[] getArray() {
            return array;
        }

        public int getExpectedMax() {
            return expectedMax;
        }
    }

    @Parameterized.Parameter
    public ArrayAndExpectedMax param;

    @Parameterized.Parameters
    public static Collection<ArrayAndExpectedMax> data(){
        return Arrays.asList(new ArrayAndExpectedMax(new int[] {1, 2, 3, 4}, 4),
                             new ArrayAndExpectedMax(new int[] {20, 30, 40, 50}, 50));
    }

    @Test
    public void testMaxInArray(){
        MaxInArray maxInArray = new MaxInArray();
        Assert.assertEquals(param.getExpectedMax(), maxInArray.findMax(param.getArray()));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM