簡體   English   中英

單元測試斷言在幾種情況下都是正確的

[英]Unit test assertion that is true in several cases

我正在嘗試編寫單元測試,我檢查某個結果是否正確。 但是,有兩個結果被認為是正確的。 有沒有辦法對斷言進行OR? 我知道我可以做結果= x || result = y並斷言這是真的。 但不是看到真實!=假,我想看到結果!= x或y。

我正在使用的框架是mstest,但我也願意聽取有關nunit的建議。

您可以嘗試Fluent Assertions 這是一組.NET擴展方法,允許您更自然地指定預期的結果測試。 Fluent Assertions支持MSTest和NUnit,因此稍后切換到nUnit並不是什么大問題。 然后,您可以使用以下代碼段表達您的斷言:

// 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.

NUnit中有一個很好的基於約束的斷言模型 它允許定義復合約束。 詳情請見此處

在你的情況下,assert可能會寫:

Assert.That(result, Is.EqualTo(1).Or.EqualTo(5));

失敗的測試消息將是(例如):
預計:1或5
但是:10

你可以做:

Assert.IsTrue( result == x || result == y );

最簡單的選擇是使用Assert.IsTrue ,但也會在失敗時傳遞一個字符串消息進行打印。 該字符串可以提供有關現實未能達到預期的信息:

Assert.IsTrue(result == x || result == y, "Result was not x or y");

您還可以輕松地在自定義消息中包含實際值:

Assert.IsTrue(result == x || result == y, "Result was not x or y, instead it was {0}", result);

或者,您可以將“正確”值存儲在Collection中,然后使用CollectionAssert.Contains

如果實際結果可以匹配兩個以上的預期值,您可以創建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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM