[英]Unit test assertion that is true in several cases
I am trying to write a unit test where I check that a certain result is correct. 我正在尝试编写单元测试,我检查某个结果是否正确。 However, there are two results that would be considered correct. 但是,有两个结果被认为是正确的。 Is there a way to do an OR with assertions? 有没有办法对断言进行OR? I know that I could do result = x || 我知道我可以做结果= x || result = y and assert that this is true. result = y并断言这是真的。 But rather than seeing true != false, I would like to see result != x or y. 但不是看到真实!=假,我想看到结果!= x或y。
The framework I am using is mstest, but I would be open to hearing suggestions for nunit as well. 我正在使用的框架是mstest,但我也愿意听取有关nunit的建议。
You could try Fluent Assertions . 您可以尝试Fluent Assertions 。 This is a set of .NET extension methods that allow you to more naturally specify the expected outcome test. 这是一组.NET扩展方法,允许您更自然地指定预期的结果测试。 Fluent Assertions supports both MSTest and NUnit, so it will be not a big deal to switch later to nUnit. Fluent Assertions支持MSTest和NUnit,因此稍后切换到nUnit并不是什么大问题。 Then you could express your assertion using following snippet: 然后,您可以使用以下代码段表达您的断言:
// Act phase: you get result somehow
var result = 42;
// Assert phase
result.Should().BeOneOf(new [] { 1, 2 } );
// in this case you'll be following error:
// Expected value to be one of {1, 41}, but found 42.
There is a nice Constraint-Based Assert Model in NUnit. NUnit中有一个很好的基于约束的断言模型 。 It allows to define compound constraints. 它允许定义复合约束。 See details here 详情请见此处
In your case assert might write: 在你的情况下,assert可能会写:
Assert.That(result, Is.EqualTo(1).Or.EqualTo(5));
The failed test message would be (eg): 失败的测试消息将是(例如):
Expected: 1 or 5 预计:1或5
But was: 10 但是:10
你可以做:
Assert.IsTrue( result == x || result == y );
The easiest option is to just use Assert.IsTrue
, but also pass a string message to print upon failure. 最简单的选择是使用Assert.IsTrue
,但也会在失败时传递一个字符串消息进行打印。 That string can give the information about how the reality failed to meet the expectation: 该字符串可以提供有关现实未能达到预期的信息:
Assert.IsTrue(result == x || result == y, "Result was not x or y");
You can easily include the actual value in your custom message also: 您还可以轻松地在自定义消息中包含实际值:
Assert.IsTrue(result == x || result == y, "Result was not x or y, instead it was {0}", result);
Alternatively, you could store your "correct" values in a Collection and then use CollectionAssert.Contains
. 或者,您可以将“正确”值存储在Collection中,然后使用CollectionAssert.Contains
。
You can create your Assert method in case the actual result could match more than two expected values: 如果实际结果可以匹配两个以上的预期值,您可以创建Assert方法:
public void AssertMultipleValues<T>(object actual, params object[] expectedResults)
{
Assert.IsInstanceOfType(actual, typeof(T));
bool isExpectedResult = false;
foreach (object expectedResult in expectedResults)
{
if(actual.Equals(expectedResult))
{
isExpectedResult = true;
}
}
Assert.IsTrue(isExpectedResult, "The actual object '{0}' was not found in the expected results", actual);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.