2010-11-09 29 views
36

在C#我怎樣才能單元測試比條件更大?C#單元測試,如何測試大於

即,i如果記錄數超過5測試成功更大。

任何幫助表示讚賞

代碼:

int actualcount = target.GetCompanyEmployees().Count 
Assert. ? 

回答

72
Assert.IsTrue(actualCount > 5, "The actualCount was not greater than five"); 
+0

但最好把一條消息,讓你知道爲什麼測試失敗:Assert.IsTrue(actualCount> 5,「actualCount不超過五」); – McKay 2010-11-09 20:20:54

+0

謝謝,它解決了 – kayak 2010-11-09 20:21:12

+4

@McKay:我個人發現這是浪費精力。如果測試失敗,無論如何我都會查看它的代碼,所以即使失敗時也不會節省很多時間*並且大多數斷言在第一次簽入IME後永遠不會失敗。 – 2010-11-09 20:23:23

6

正確的方式使用NUnit時,要做到這一點:

Assert.That(actualcount , Is.GreaterThan(5)); 
+8

'Microsoft.VisualStudio.TestTools.UnitTesting.Assert'不包含'That'的定義。在VS 2012. – 2013-08-13 18:02:33

+0

也沒有GreaterThan,也沒有LessThan,也沒有... – stannius 2015-01-11 22:52:33

+2

只適用於nUnit! (但是謝謝T提示:-)) – ShloEmi 2015-12-15 14:55:56

0

actualCount.Should().BeGreaterThan(5);

+1

看起來不錯,這是Extension Method的?什麼名稱空間來定義? – ShloEmi 2015-12-15 14:53:42

+0

這隻適用於FluentAssertions,但是@ShloEmi告訴NKnusperer,對於那些使用它的人來說是一個很好的提示。 – RoLYroLLs 2015-12-16 06:28:29

4

A G eneric解決方案,它可以與任何可比的類型可以使用:

public static T ShouldBeGreaterThan<T>(this T actual, T expected, string message = null) 
    where T: IComparable 
{ 
    Assert.IsTrue(actual.CompareTo(expected) > 0, message); 
    return actual; 
} 
0

中的xUnit是:

[Fact] 
    public void ItShouldReturnErrorCountGreaterThanZero() 
    { 
     Assert.True(_model.ErrorCount > 0); 
    }