【发布时间】:2011-01-08 17:45:52
【问题描述】:
我有一个依赖随机掷骰子的单元测试。我掷了一个 20 面的骰子,如果值为 20,则视为重击。
我现在正在做的是将 20 面骰子滚动 300 次。如果其中任何一个结果是 20,那么我知道我受到了重击。
代码如下:
public class DiceRoll
{
public int Value { get; set; }
public bool IsCritical { get; set; }
// code here that sets IsCritical to true if "Value" gets set to 20
}
[Test]
public void DiceCanRollCriticalStrikes()
{
bool IsSuccessful = false;
DiceRoll diceRoll = new DiceRoll();
for(int i=0; i<300; i++)
{
diceRoll.Value = Dice.Roll(1, 20); // roll 20 sided die once
if(diceRoll.Value == 20 && diceRoll.IsCritical)
{
IsSuccessful = true;
break;
}
}
if(IsSuccessful)
// test passed
else
// test failed
}
虽然测试完全符合我的要求,但我还是忍不住觉得自己做错了什么。
在相关说明中,DiceRoll 类中还有其他信息,但我的问题是关于单元测试中的循环,所以我将其省略以使其更清楚
【问题讨论】:
标签: c# unit-testing loops dice