Skip to content

Equal.Within Fails With Negative Tolerance #4876

Description

@RaffaelCH

Summary

If asserting the equality of two floats within a tolerance (Is.EqualTo.Within), a negative tolerance leads to the test always failing. No warning is being reported, instead the test simply fails with the default error message. From the error message it is unclear that the reason for the test failing is the negative tolerance.

This can be an issue in the case of the tolerance being calculated, if the resulting tolerance can be negative.

Example

Versions: .NET 8, NUnit 4.3.0 (although was also observed in 3.9).

Given a test which compares the equality of two floats with a negative tolerance as follows:

[Test]
public void NegativeToleranceTest()
{
    Assert.That(2f, Is.EqualTo(2f).Within(-0.1f), "Negative Tolerance");
}

This test, when being executed, reports the following message:

Negative Tolerance
Expected: 2.0f +/- -0.100000001f
But was: 2.0f
Off by: 0.0d

From a mathematical standpoint this message does not make sense, as 2 +/- -0.1 == 2 -/+ 0.1. This makes it unnecessarily hard to find this issue.

Proposed Solution

Introduce a warning (preferrably compile-time) for negative tolerances, at least for built-in number formats.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions