C# unit test, how to test greater than

57,695

Solution 1

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

Solution 2

It depends on which testing framework you're using.

For xUnit.net:

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

For NUnit:

Assert.Greater(actualCount, 5);; however, the new syntax

Assert.That(actualCount, Is.GreaterThan(5)); is encouraged.

For MSTest:

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

Solution 3

The right way to do this when using nUnit is:

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

Solution 4

xUnit: if you know upper bound (=100 in example), you can use:

Assert.InRange(actualCount, 5, 100);

Solution 5

A generic solution that can be used with any comparable type:

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;
}
Share:
57,695

Related videos on Youtube

kayak
Author by

kayak

Updated on November 10, 2021

Comments

  • kayak
    kayak over 2 years

    In C# how can I unit test a greater than condition?

    I.e., iIf record count is greater than 5 the test succeed.

    Any help is appreciated

    Code:

    int actualcount = target.GetCompanyEmployees().Count
    Assert. ?
    
  • McKay
    McKay over 13 years
    But it's best to put a message so that you know why the test failed: Assert.IsTrue(actualCount > 5, "The actualCount was not greater than five");
  • Jon Skeet
    Jon Skeet over 13 years
    @McKay: I personally find that a wasted effort. If the test fails, I'm going to look at its code anyway, so it wouldn't save much time even when it fails and the majority of assertions are never going to fail after the first check-in IME.
  • McKay
    McKay over 13 years
    Well, frequently, I write tests in a manner that the test code will be run for a bunch of different tests. So while I will look at the code, I don't always look at the code that does the assertions, because they're not always close together.
  • Wix
    Wix over 13 years
    @Sri: Mark as answer, please.
  • Ray Cheng
    Ray Cheng almost 11 years
    'Microsoft.VisualStudio.TestTools.UnitTesting.Assert' does not contain a definition for 'That'. in VS 2012.
  • ShloEmi
    ShloEmi over 8 years
    Looks good, this is Extension Method of ? what namespace to define?
  • RoLYroLLs
    RoLYroLLs over 8 years
    This is only good for FluentAssertions, but as @ShloEmi told NKnusperer, good tip for those using it.
  • Timothy
    Timothy over 5 years
    If you're more inclined to use the classic assert style for NUnit, another option is Assert.Greater(actualcount, 5);