C# unit test, how to test greater than

C#Unit TestingTesting

C# 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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkayakView Question on Stackoverflow
Solution 1 - C#WixView Answer on Stackoverflow
Solution 2 - C#Tobias FeilView Answer on Stackoverflow
Solution 3 - C#NKnuspererView Answer on Stackoverflow
Solution 4 - C#MarinaView Answer on Stackoverflow
Solution 5 - C#holdenmcgrohenView Answer on Stackoverflow
Solution 6 - C#Rakesh AndrotulaView Answer on Stackoverflow
Solution 7 - C#Adam SeabridgeView Answer on Stackoverflow
Solution 8 - C#Ali KleitView Answer on Stackoverflow