Search Results for

    Show / Hide Table of Contents

    LessThanOrEqual Constraint

    LessThanOrEqualConstraint tests that one value is less than or equal to 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.LessThanOrEqualTo(object expected)
    Is.AtMost(object expected)               // Alias for LessThanOrEqualTo
    

    Modifiers

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

    Examples

    [Test]
    public void LessThanOrEqualConstraint_Examples()
    {
        Assert.That(7, Is.LessThanOrEqualTo(7));
        Assert.That(3, Is.LessThanOrEqualTo(7));
        Assert.That(3, Is.AtMost(7));
    
        // With DateTime
        Assert.That(DateTime.Today, Is.LessThanOrEqualTo(DateTime.Now));
    
        // With tolerance
        Assert.That(9.9, Is.LessThanOrEqualTo(10.0).Within(0.5));
    }
    

    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. Is.AtMost is a more readable alias for Is.LessThanOrEqualTo.
    2. When comparing floating-point numbers, consider using .Within() to specify a tolerance.

    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