BlackWaspTM
Testing
.NET 1.1+

NUnit Comparison Assertions

The sixth part of the Automated Unit Testing tutorial continues the description of the assertion commands provided by the NUnit framework. This instalment looks at comparison asserts, which ensure that a result is greater or less than an expected value.

Comparison Asserts

The comparison asserts allow you to compare two values in your tests and assert that one is greater than or less than the other, providing similar functionality to conditions that contain relational operators. As with the equality assertions, if the condition you specify is not met the test is reported as a failure in the NUnit test runner.

In this article we will create some tests for a sample method. The method generates strings that contain a repeating character and are of a length that is randomly generated according to provided minimum and maximum values. The code is as follows:

public class StringGenerator
{
    Random _random = new Random();

    public string Generate(char character, int minLength, int maxLength)
    {
        int length = _random.Next(minLength, maxLength + 1);
        return new string(character, length);
    }
}

Assert.Less

The first of the comparison assertions is provided by the Less method. This is a static method of the Assert class. You should use Assert.Less when you do not know the exact expected result of an operation but want to ensure that a generated result is less than an expected value. The assertion can work with numeric data types and any other type that implements the IComparable interface.

The example below calls the Generate method with a length range of six to ten characters. The assertion ensures that the resultant string has fewer than eleven characters. Note the order of the parameters; the statement Assert.Less(a,b) ensures that a is less than b. This order pattern is the same for all of the comparison asserts.

[TestFixture]
public class AdderTests
{
    StringGenerator _generator = new StringGenerator();
    string _result;

    [SetUp]
    public void SetUp()
    {
        _result = _generator.Generate('*', 6, 10);
    }

    [Test]
    public void ResultantStringIsLessThan11Chars()
    {
        Assert.Less(_result.Length, 11);
    }
}
9 April 2011