2010-11-09 57 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); 
    }