java - 如何在 JUnit 中为此类编写单元测试

标签 java unit-testing random junit mocking

//如何在JUnit中为这个类编写单元测试......

package com.emr.common.helper;

import java.util.Random;

public class RandomTextGenerator {

    public static String getAutogenerateText()
    {
        /*Auto genarate password    */

        String password = "";
        /* Create Auto Password */
        int count = 36;
        // int range = Integer.MAX_VALUE;
        int sum = 0;

        Random rand = new Random();
        for (int j = 0; j < 45; j++) {
            for (int i = 0; i < count; i++) {
                sum = rand.nextInt(count);

            }
            char[] pass = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
                    'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7',
                    '8', '9' };
            password = password + pass[sum];
        }

        return password;
    }

}

最佳答案

如果你说new Random(),你将无法有效地测试这个类 - 通过这样做,你已经硬编码了对有效外部依赖项的引用(随机数),你无法控制。

相反,您应该通过方法参数将 Random 对象传递到类中,并在您的测试中提供一个模拟实现,您可以控制返回的值。

关于java - 如何在 JUnit 中为此类编写单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15942808/

相关文章:

javascript - Angular Controller Mock 在我的 Mocha 测试中没有持续存在

unit-testing - 如何测试容器类?

java - 随机但每个只能出现一次

java - 在循环中随机填充的值范围

java - 是否可以保证 java.util.Collections.shuffle() 背后的算法在未来的 Java 版本中保持不变?

java - 为什么堆栈使用数组为什么不使用链表

java - 什么是NullPointerException,我该如何解决?

java - 将带有换行符的固定长度的文本文件作为属性值之一读入 JavaRDD

unit-testing - RSpec: 'allow_any_instance_of' 的替代方法是什么?

具有可抢占线程队列的java执行器