【问题标题】:how to write unit test for this class in JUnit如何在 JUnit 中为此类编写单元测试
【发布时间】:2013-04-11 07:16:39
【问题描述】:

//如何在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;
    }

}

【问题讨论】:

  • 你有什么问题?
  • 你想明确测试什么?你想持有什么条件?

标签: java unit-testing random junit mocking


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    尝试将其与 RegEx 进行匹配,该 RegEx 检查返回的字符串是否匹配 45 个字母和数字混合的字符。

    这个正则表达式应该可以工作:

    ^[A-Z0-9]{45}$
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 2021-02-03
      • 2022-11-04
      • 1970-01-01
      • 2019-12-22
      • 2018-01-09
      • 1970-01-01
      相关资源
      最近更新 更多