单元测试 - 自动生成数组或其它数据的java库?
迷茫
迷茫 2017-04-18 10:48:41
0
2
613

比如说, 我希望验证一个排序算法是否正确. 我不想自己去写测试数据, 有没有什么库能够自动生成包含数据的数组或其它的容器类.

比如能够自动生成一个长度为100的有序int数组等等.

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
巴扎黑

Keywords, shuffle

    public static List<Integer> generateRandomArray(int len)
    {
        if(len <= 0)
        {
            throw new IllegalArgumentException(len + " can not be negitive.");
        }
        List<Integer> arr = new ArrayList<>(len);
        for(int i = 0; i < len; i++)
        {
            arr.add(i);
        }
        Collections.shuffle(arr);
        return arr;
    }
Ty80

I have never heard of such a library - but for this kind of simple method, I suggest "do it yourself and have enough food and clothing". Based on your current foundation, you should think more, write more and practice more - implementing this type of method yourself is a good foundation-laying process.

What you need now is not a method to generate an ordered array. What you need is the following two methods:

Generate an unordered integer array of length n. The range of the array elements is 0 ~ bound:

public int[] randomArray(int n, int bound) {
    Random random = new Random();

    int[] array = new int[n];
    for (int i = 0; i < n; i++) {
        array[i] = random.nextInt(bound);
    }

    return array;
}

Determine whether array is sorted in ascending order:

public boolean isAscending(int[] array) {
    for (int i = 1; i < array.length; i++) {
        if (array[i - 1] > array[i]) { // 判断降序的话,将 > 改成 <
            return false;
        }
    }
    return true;
}

With these two methods, you can generate an integer array for sorting and determine whether the integer array is in order.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template