以下代码用于玩彩票游戏。
let Lotto = {
_nMap: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50
],
_sMap: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
],
/**
* @param {Array} shuffleArr
*
* @return {Array}
*/
_shuffleArr(shuffleArr) {
let rndNr, tmpValue;
for (let elmNr = shuffleArr.length - 1; elmNr > 0; elmNr--) {
rndNr = Math.floor(
Math.random() * (elmNr + 1)
);
tmpValue = shuffleArr[rndNr];
shuffleArr[rndNr] = shuffleArr[elmNr];
shuffleArr[elmNr] = tmpValue;
}
return shuffleArr;
},
/**
* @return {Object}
*/
getPick() {
return {
n: this._shuffleArr(this._nMap).slice(0, 5),
s: this._shuffleArr(this._sMap).slice(0, 2)
}
}
};
现在我想验证实现是否正确。例如:它应该返回一组唯一的数字。我该如何测试?运行.getPick()方法一次并验证输出或......?
答案 0 :(得分:0)
您可以编写一个测试用例,让脚本运行10到15次,然后将值放在数组中并找到模式。这样的事情会很好:
let Lotto = {
_nMap: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50
],
_sMap: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
],
/**
* @param {Array} shuffleArr
*
* @return {Array}
*/
_shuffleArr(shuffleArr) {
let rndNr, tmpValue;
for (let elmNr = shuffleArr.length - 1; elmNr > 0; elmNr--) {
rndNr = Math.floor(
Math.random() * (elmNr + 1)
);
tmpValue = shuffleArr[rndNr];
shuffleArr[rndNr] = shuffleArr[elmNr];
shuffleArr[elmNr] = tmpValue;
}
return shuffleArr;
},
/**
* @return {Object}
*/
getPick() {
return {
n: this._shuffleArr(this._nMap).slice(0, 5),
s: this._shuffleArr(this._sMap).slice(0, 2)
}
}
};
var entries = [];
for (var i = 0; i < 100; i++)
entries.push(JSON.stringify(Lotto.getPick()));
var counts = {};
for (var i = 0; i < entries.length; i++) {
counts[entries[i]] = 1 + (counts[entries[i]] || 0);
}
console.log(counts);
if (Object.keys(counts).length == 100)
alert("Excellent, 0 dupes!");
else if (Object.keys(counts).length > 75)
alert("More than 75% unique.");
else
alert("Less than 75% unique.");
在这里,我发现每个输出都是独一无二的。这就是您需要自动化或编写测试用例的方法。上面的代码片段本身就是一个测试解决方案。尝试一下,让我知道它是否适合您。