单元测试,如何测试大于

在 C # 中,如何进行大于条件的单元测试?

例如,如果记录计数大于5,则测试成功。

感谢你的帮助

密码:

int actualcount = target.GetCompanyEmployees().Count
Assert. ?
63007 次浏览
Assert.IsTrue(actualCount > 5, "The actualCount was not greater than five");

The right way to do this when using nUnit is:

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

actualCount.Should().BeGreaterThan(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;
}

in XUnit it's:

    [Fact]
public void ItShouldReturnErrorCountGreaterThanZero()
{
Assert.True(_model.ErrorCount > 0);
}

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

Assert.InRange(actualCount, 5, 100);

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.");

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)