首页  >  问答  >  正文

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

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

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

迷茫迷茫2744 天前579

全部回复(2)我来回复

  • 巴扎黑

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

    关键词,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;
        }

    回复
    0
  • PHP中文网

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

    这样的库,还真没有听说过 —— 但是这类简单的方法,我建议 “自己动手,丰衣足食”。以你现在的基础而言,你应该多思考,多写多练 —— 自己去实现这类方法,就是很好的打基础的过程。

    你现在需要的并不是一个生成有序数组的方法。你需要的是下面两个方法:

    生成一个长度为 n 的无序整数数组,数组元素的范围为 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;
    }

    判断 array 是否是升序排序:

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

    有了这两个方法,便可以生成用于排序的整数数组和对整数数组是否有序进行判断。

    回复
    0
  • 取消回复