【发布时间】:2015-08-16 19:21:01
【问题描述】:
我有一个生成伪随机数的程序(只允许小写、大写和数字)。
/**
*
* @return - returns a random digit (from 0 to 9)
*
*/
int randomDigits() {
return (int) (Math.random() * 10);
}
/**
*
* @return - returns a random lowercase (from "a" to "z")
*/
char randomLowerCase() {
return (char) ('a' + Math.random() * 26);
}
/**
*
* @return - returns a random uppercase (from "A" to "Z")
*/
char randomUpperCase() {
return (char) ('A' + Math.random() * 26);
}
/**
*
* @return - returns a random number between 1 and 3.
*
*/
char randomChoice() {
return (char) ((char) (Math.random() * 3) + 1);
}
/**
*
* @param length
* - the length of the random string.
* @return - returns a combined random string. All elements are builder side
* by side.
*
* We use the randomChoice method to get randomly upper, lower and
* digits.
*/
public String stringBuilder(int length) {
StringBuilder result = new StringBuilder();
int len = length;
for (int i = 0; i < len; i++) {
int ch = randomChoice();
if (ch == 1) {
result.append(randomDigits());
}
if (ch == 2) {
result.append(randomLowerCase());
}
if (ch == 3) {
result.append(randomUpperCase());
}
}
return result.toString();
}
我怎样才能对该代码进行测试。我尝试测试数字的范围(从 0 到 9)
int minRange = 0;
int maxRange = 0;
for (int i = 0; i < 100000; i++) {
int result = item.randomDigits();
if (result == 52) {
minRange++;
} else {
if (result == 19) {
maxRange++;
}
}
}
LOGGER.info("The min range in the digit is 0, and in the test appeared: {}", minRange);
LOGGER.info("The max range in the digit is 9, and in the test appeared: {}", maxRange);
但我找不到如何测试下层或上层?
【问题讨论】:
-
尝试随机字符串它不是很有用,这是程序的目标?
-
RandomStrings item = new RandomStrings();
-
所以看起来
minRange正在尝试计算 0 的出现次数,而maxRange正在尝试计算 9 的出现次数。但是,您正在检查 52 ( != 0 ) 和 19 (!= 9)。那么你真正想要测试的是什么? -
你看过stackoverflow.com/questions/363681/…吗?您的问题与这些答案无济于事有何不同?
-
需要自己写吗?我总是只使用 Commons Lang
RandomStringUtils。