C#单元测试,如何测试大于

kay*_*yak 52 c# testing unit-testing

在C#中我怎样才能测试大于条件?

即,如果记录计数大于5,则测试成功.

任何帮助表示赞赏

码:

int actualcount = target.GetCompanyEmployees().Count
Assert. ?
Run Code Online (Sandbox Code Playgroud)

Wix*_*Wix 106

Assert.IsTrue(actualCount > 5, "The actualCount was not greater than five");
Run Code Online (Sandbox Code Playgroud)

  • @McKay:我个人觉得这是一种浪费的努力.如果测试失败了,我将继续查看它的代码,因此即使它失败也不会节省太多时间*并且大多数断言在第一次签入IME后永远不会失败. (4认同)
  • 但最好放一条消息,以便您知道测试失败的原因: Assert.IsTrue(actualCount > 5, "The actualCount was not大于 5"); (3认同)
  • 好吧,我经常以一种方式编写测试,测试代码将运行一堆不同的测试.因此,虽然我将查看代码,但我并不总是查看执行断言的代码,因为它们并不总是紧密相连. (2认同)

NKn*_*rer 12

使用nUnit时执行此操作的正确方法是:

Assert.That(actualcount , Is.GreaterThan(5));
Run Code Online (Sandbox Code Playgroud)

  • 'Microsoft.VisualStudio.TestTools.UnitTesting.Assert'不包含'That'的定义.在VS 2012中. (8认同)
  • 只适用于nUnit!(但感谢T提示:-)) (2认同)
  • 如果您更倾向于使用 NUnit 的经典断言样式,另一种选择是 `Assert.Greater(actualcount, 5);` (2认同)

小智 5

xUnit:如果您知道上限(例如 =100),您可以使用:

Assert.InRange(actualCount, 5, 100);
Run Code Online (Sandbox Code Playgroud)


Tob*_*eil 5

这取决于您使用的测试框架。

对于xUnit.net:

Assert.True(actualCount > 5, "Expected actualCount to be greater than 5.");

对于NUnit:

Assert.Greater(actualCount, 5);; 但是,新语法

Assert.That(actualCount, Is.GreaterThan(5)); 被鼓励。

对于MSTest:

Assert.IsTrue(actualCount > 5, "Expected actualCount to be greater than 5.");