C# NUnit:断言三个或更多的值是相同的
我需要断言三个值是相同的 例如,我需要这样的东西C# NUnit:断言三个或更多的值是相同的,c#,nunit,C#,Nunit,我需要断言三个值是相同的 例如,我需要这样的东西 Assert.AreEqual(person1.Name, person2.Name, person3.Name); Assert.That(person1.Name, Is.EqualTo(person2.Name), Is.EqualTo(person3.Name)); 这两个方法只允许比较两个值(前两个参数),第三个参数是输出消息 我知道CollectionAssert,但我不想仅为这种情况创建IEnumerables 是否可以在不使用
Assert.AreEqual(person1.Name, person2.Name, person3.Name);
Assert.That(person1.Name, Is.EqualTo(person2.Name), Is.EqualTo(person3.Name));
这两个方法只允许比较两个值(前两个参数),第三个参数是输出消息
我知道CollectionAssert
,但我不想仅为这种情况创建IEnumerables
是否可以在不使用集合的情况下比较NUnit中的两个以上参数?接受
参数[]
或其他内容的某些方法。您可以执行两个单独的断言:
Assert.AreEqual(person1.Name, person2.Name);
Assert.AreEqual(person1.Name, person3.Name);
或者您可以创建一个助手函数:
public static class AssertEx
{
public static void AllAreEqual<T>(params T[] items)
{
for (int i = 1; i < items.Length; i++)
{
Assert.AreEqual(items[0], items[i]);
}
}
}
您可以使用以下语法:
给予
Expected: "b" and "a"
But was: "a"
1 passed, 1 failed, 0 skipped, took 1.09 seconds (NUnit 2.5.5).
另外需要考虑的是单元测试的第一条规则是“每个测试一个断言”,这可以更快地识别问题所在。如果你断言所有3个匹配,那么如果其中一个不匹配,那么你必须找出哪一个
public void All_Values_Match()
{
Assert.AreEqual(person1.Name, person2.Name);
Assert.AreEqual(person1.Name, person3.Name);
}
如果你按照
public void First_Second_Values_Match()
{
Assert.AreEqual(person1.Name, person2.Name);
}
public void First_Third_Values_Match()
{
Assert.AreEqual(person1.Name, person3.Name);
}
这将提供更清晰的测试结果 你不能只用两个断言吗?当然可以,但我不想有200行断言,因为我可以有100行。
Expected: "b" and "a"
But was: "a"
1 passed, 1 failed, 0 skipped, took 1.09 seconds (NUnit 2.5.5).
public void All_Values_Match()
{
Assert.AreEqual(person1.Name, person2.Name);
Assert.AreEqual(person1.Name, person3.Name);
}
public void First_Second_Values_Match()
{
Assert.AreEqual(person1.Name, person2.Name);
}
public void First_Third_Values_Match()
{
Assert.AreEqual(person1.Name, person3.Name);
}