Home  >  Q&A  >  body text

单元测试 - 自动生成数组或其它数据的java库?

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

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

迷茫迷茫2764 days ago595

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-18 10:50:41

    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;
        }

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:50:41

    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.

    reply
    0
  • Cancelreply