C# unit test, how to test greater than
C#Unit TestingTestingC# Problem Overview
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. ?
C# Solutions
Solution 1 - C#
Assert.IsTrue(actualCount > 5, "The actualCount was not greater than five");
Solution 2 - C#
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 - C#
The right way to do this when using nUnit is:
Assert.That(actualcount , Is.GreaterThan(5));
Solution 4 - C#
xUnit: if you know upper bound (=100 in example), you can use:
Assert.InRange(actualCount, 5, 100);
Solution 5 - C#
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;
}
Solution 6 - C#
actualCount.Should().BeGreaterThan(5);
Solution 7 - C#
in XUnit it's:
[Fact]
public void ItShouldReturnErrorCountGreaterThanZero()
{
Assert.True(_model.ErrorCount > 0);
}
Solution 8 - C#
In addition to the good answers, you can always have a helper class:
public static class AssertHelper
{
public static void Greater(int arg1, int arg2, string message = null)
{
Assert.IsTrue(arg1 > arg2, message);
}
public static void NotZero(int number, string message = null)
{
Assert.IsTrue(number != 0, message);
}
public static void NotNull(object obj, string message = null)
{
Assert.IsTrue(obj != null, message);
}
public static void IsNotEmpty(string str, string message = null)
{
Assert.IsTrue(str != string.Empty, message);
}
// etc...
}
Usage:
AssertHelper.Greater(n1,n2)