LessThan Constraint
LessThanConstraint tests that one value is less 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.LessThan(object expected)
Is.Negative // Equivalent to Is.LessThan(0)
Modifiers
.Using(IComparer comparer)
.Using<T>(IComparer<T> comparer)
.Using<T>(Comparison<T> comparer)
.Within(object tolerance)
Examples
[Test]
public void LessThanConstraint_Examples()
{
Assert.That(3, Is.LessThan(7));
Assert.That(-5, Is.Negative);
Assert.That(5, Is.Not.Negative);
// With DateTime
Assert.That(DateTime.Today, Is.LessThan(DateTime.Now));
// With tolerance
Assert.That(9.5, Is.LessThan(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
- When comparing floating-point numbers, consider using
.Within()to specify a tolerance. Is.Negativeis a convenience shorthand forIs.LessThan(0).