我正在编写一些N-Unit测试,我遇到了一些困难。我试图在代码中将一个Test连接到一个TestCaseSource,但它似乎没有正确地构造对象。
以下是我的测试方法:
[Test, TestCaseSource(typeof(TestCaseStuff), "GetTestCases", Category = "Release")]
public void WithdrawMoney(TestCaseStuff tc)
{
double newBalance = AccountBalance - tc.amt;
if (newBalance < 0)
{
Assert.Fail(String.Format("You can't withdraw {0}! You've maxed" +
"out your bank account.", tc.amt.ToString("C2")));
}
AccountBalance = newBalance;
Assert.Pass(String.Format("Your new balance is {0}.",
(AccountBalance).ToString("C2")));
}还有我的TestCaseSource
public class TestCaseStuff
{
public double amt { get; set; }
public TestCaseStuff()
{
Random rnd = new Random();
this.amt = rnd.Next(0, 20);
}
[Category("Release")]
public IEnumerable<TestCaseData> GetTestCases()
{
for (int i = 0; i < 500; i++)
{
yield return new TestCaseData(this);
}
}
}但是,返回到我的测试方法的每个TestCaseStuff实例都是相同的。
更新:
下面的答案是正确的。当我将它传递给N单元TestCaseData对象时,我假设(错误地)它会简单地通过值传递该实例。显然,它是通过引用来完成的,这就是为什么值总是相同的原因。
最重要的是,我错误地使用了Random类。这不是我通常要处理的事情,但我没有正确地阅读它。正如在下面的链接中所解释的,当将Random与其默认构造函数一起使用时,种子值是从系统时钟派生的。因此,如果您快速连续地实例化多个Random对象,它们将共享相同的默认种子值并生成相同的值。
因此,作为这些开发的结果,我的代码现在是:
public class TestCaseStuff
{
public double amt { get; set; }
private static readonly Random rnd = new Random();
public TestCaseStuff()
{
this.amt = rnd.Next(0, 20);
}
[Category("Release")]
public IEnumerable<TestCaseData> GetTestCases()
{
for (int i = 0; i < 500; i++)
{
yield return new TestCaseData(new TestCaseStuff());
}
}
}发布于 2012-10-10 23:03:13
上面的代码将只实例化TestCaseSource的一个副本,并继续提供相同的值。
如果目的是在每个循环中生成一个随机数,我认为您应该创建一个Random对象的静态实例,并在每次创建新的TestCaseStuff对象时从它生成一个数字。
我会像这样重写TestCaseStuff:
public class TestCaseStuff
{
// Static instance of a random number generator.
private static readonly Random RNG = new Random();
public double amt { get; set; }
public TestCaseStuff()
{
this.amt = RNG.Next(0, 20);
}
[Category("Release")]
public IEnumerable<TestCaseData> GetTestCases()
{
for (int i = 0; i < 500; i++)
{
// NOTE: You need to create a new instance here.
yield return new TestCaseData(new TestCaseStuff());
}
}
}发布于 2012-10-10 22:49:26
每次调用都会创建一个新的Random实例:
yield return new TestCaseData(this);试着把它移到循环之外,你应该开始得到随机值了。
我发现这篇文章很好地解释了这一点!How do I seed a random class to avoid getting duplicate random values
https://stackoverflow.com/questions/12821867
复制相似问题