Search Results for

    Show / Hide Table of Contents

    GreaterThan Constraint

    GreaterThanConstraint tests that one value is greater than another. It works with numeric types, DateTime, TimeSpan, and any type implementing IComparable. For custom types, a user-specified comparer can be provided using the Using modifier.

    Usage

    Is.GreaterThan(object expected)
    Is.Positive                      // Equivalent to Is.GreaterThan(0)
    

    Modifiers

    .Using(IComparer comparer)
    .Using<T>(IComparer<T> comparer)
    .Using<T>(Comparison<T> comparer)
    .Within(object tolerance)
    

    Examples

    [Test]
    public void GreaterThanConstraint_Examples()
    {
        Assert.That(7, Is.GreaterThan(3));
        Assert.That(5, Is.Positive);
        Assert.That(-3, Is.Not.Positive);
    
        // With DateTime
        Assert.That(DateTime.Now, Is.GreaterThan(DateTime.Today));
    
        // With tolerance
        Assert.That(10.5, Is.GreaterThan(10.0).Within(0.1));
    }
    

    Using Custom Comparers

    public class MyOwnObject(int age)
    {
        public int Age => age;
    }
    
    /// <summary>
    /// Comparer handling different types of objects (MyOwnObject and int) and comparing them based on the Age property of MyOwnObject instances.
    /// </summary>
    public class MyComparerUntyped : IComparer
    {
        public int Compare(object? x, object? y)
        {
            // Handle nulls
            if (ReferenceEquals(x, y)) return 0;
            if (x is null) return -1;
            if (y is null) return 1;
            // Identify which one is the object and which is the int
            int actualAge = x is MyOwnObject obj ? obj.Age : (int)x;
            int expectedAge = y is MyOwnObject objY ? objY.Age : (int)y;
    
            return actualAge.CompareTo(expectedAge);
        }
    }
    
    /// <summary>
    /// High performance comparer for equal typed objects that only compares the Age property of MyOwnObject instances.
    /// </summary>
    public class MyComparerTyped : IComparer<MyOwnObject>
    {
        public int Compare(MyOwnObject? x, MyOwnObject? y)
        {
            if (ReferenceEquals(x, y)) return 0;
            if (x is null) return -1;
            if (y is null) return 1;
    
            return x.Age.CompareTo(y.Age);
        }
    }
    
    

    Notes

    1. When comparing floating-point numbers, consider using .Within() to specify a tolerance.
    2. Is.Positive is a convenience shorthand for Is.GreaterThan(0).

    See Also

    • LessThan Constraint
    • GreaterThanOrEqual Constraint
    • Range Constraint
    • Edit this page
    In this article
    Back to top Generated by DocFX | Copyright (c) 2018- The NUnit Project - Licensed under CC BY-NC-SA 4.0