简体   繁体   English

如何在 Java 中创建单元测试?

[英]How do I create a Unit test in Java?

I have a java class that takes an array of numbers and an array of corresponding probabilities and acts as a random number generator that returns one of the numbers from the array according to the corresponding probabilities defined in the other other.我有一个 java class ,它采用一个数字数组和一个相应概率数组,并充当随机数生成器,根据另一个数字中定义的相应概率从数组中返回一个数字。 How do I write a minimal but effective set of unit tests?如何编写最少但有效的单元测试集?

class RandomGen {

    private int[] randomNums;
    private float[] probabilities;
    private float[] total_prob;

    RandomGen(int[] randomNums, float[] probabilites) throws Exception {
        if (this.set_arrays(randomNums, probabilites));
        else {
            throw new Exception("Invalid array format");
        }
    }

    private boolean set_arrays(int[] randomNums, float[] probabilities) {
        if (check_arrays(randomNums, probabilities)) {
            this.randomNums = randomNums;
            this.probabilities = probabilities;
            this.total_prob = new float[this.probabilities.length];

            total_prob[0] = probabilities[0];
            for (int i = 1; i < probabilities.length; i++){
                total_prob[i] = total_prob[i-1] + probabilities[i];
            }
            return true;
        }
        return false;
    }

    public int[] return_randomNums() {
        return this.randomNums;
    }

    public float[] return_probabilites() {
        return this.probabilities;
    }

    private boolean check_arrays(int[] randomNums, float[] probabilities) {
        float total_prob = 0;
        for (int i = 0; i < probabilities.length; i++) {
            if (probabilities[i] < 0) return false;
            total_prob += probabilities[i];
        }
        if (randomNums.length != probabilities.length || total_prob != 1) return false;
        return true;
    }

    public int nextNum() {
        float random = (float) Math.random();
        if (random <= total_prob[0]) {
            return randomNums[0];
        }
        for (int i=1; i < total_prob.length; i++) {
            if (total_prob[i-1] < random  && random <= total_prob[i]) return randomNums[i];
        }
        return 0;
    }
}

For learning unit testing this class might be a little too complex.对于学习单元测试,这个 class 可能有点太复杂了。 We can also just scratch the surface here, as this is not something you can learn from a few examples.我们也可以在这里只触及表面,因为这不是你可以从几个例子中学到的。 I urge you to get a book on the topic.我敦促你买一本关于这个主题的书。

But since we are already here, let's have a look at your class.但是既然我们已经在这里了,让我们看看你的 class。

The public interface of your class consists of the constructor, nextNum() and the two getters (methods that just return fields are called getters, because they are usually named getFieldName() , eg getRandomNums() ).您的 class 的公共接口由构造函数nextNum()和两个 getter(仅返回字段的方法称为 getter,因为它们通常命名为getFieldName() ,例如getRandomNums() )。

The getters do not contain any logic. getter 不包含任何逻辑。 Therefore I would refrain from testing them.因此,我会避免测试它们。

Your constructor is actually doing quite a lot.您的构造函数实际上做了很多工作。 At first it checks if the arrays are valid (same length and the probabilities add up to 1) and then it stores the array and build a new array with the cumulative probabilities.首先它检查 arrays 是否有效(长度相同且概率加起来为 1),然后存储数组并使用累积概率构建一个新数组。 For testing it, each test case would create a new instance of RandomGen with different arrays that constitute different situations.为了对其进行测试,每个测试用例将创建一个新的RandomGen实例,其中包含不同的 arrays 构成不同的情况。 The three situations that are apparent are:显而易见的三种情况是:

  • the probabilities add up to one, but the two arrays have different length概率加起来为一,但两个 arrays 的长度不同
  • the two array have the same length, but the probabilities arrays elements do not add up to 1两个数组的长度相同,但 arrays 元素的概率加起来不等于 1
  • the two array have the same length and the probabilities add up to one两个数组的长度相同,概率加起来为 1

The first two cases are error cases and would expect an exception to be thrown and the last one is the "sunshine case" where you could check if the two arrays are now returned by your getters.前两种情况是错误情况,预计会引发异常,最后一种情况是“阳光情况”,您可以检查两个 arrays 现在是否由您的吸气剂返回。 The cumulative probabilities ( total_prob ) can only be observed by using nextNum() .累积概率 ( total_prob ) 只能通过使用nextNum()来观察。

Then there is the nextNum() method.然后是nextNum()方法。 This is already a bit advanced, since you can not predict the results of Math.random() .这已经有点高级了,因为您无法预测Math.random()的结果。 Possible solutions are either to use a predefined seed (as Victor Polo De Gyves Montero suggested) or to wrap and inject Math.random() .可能的解决方案是使用预定义的种子(正如 Victor Polo De Gyves Montero 建议的那样)或包装和注入Math.random() In your case I would skip that and first read a book and get some experiences with unit testing.在您的情况下,我会跳过它并首先阅读一本书并获得一些单元测试经验。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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