在使用 FluentAssertions 将可为空的类型与其基础类型进行比较时,这是一个错误吗?

本文关键字:类型 比较 错误 一个 FluentAssertions | 更新日期: 2023-09-27 18:35:23

当我遇到一个我预计会失败的测试时,我正在为实用程序库编写一些单元测试,但实际上通过了。该问题与比较两个float变量有关,与比较一个float?和一个float变量有关。

我使用的是最新版本的NUnit(2.6.0.12051)和FluentAssertions(1.7.1),下面是一个小代码截图说明这个问题:

using FluentAssertions;
using FluentAssertions.Assertions;
using NUnit.Framework;
namespace CommonUtilities.UnitTests
{
    [TestFixture]
    public class FluentAssertionsFloatAssertionTest
    {
        [Test]
        public void TestFloatEquality()
        {
            float expected = 3.14f;
            float notExpected = 1.0f;
            float actual = 3.14f;
            actual.Should().BeApproximately(expected, 0.1f);
            actual.Should().BeApproximately(notExpected, 0.1f); // A: Correctly fails (Expected value 3,14 to approximate 1 +/- 0,1, but it differed by 2,14.)
            actual.Should().BeInRange(expected, expected);
            actual.Should().BeInRange(notExpected, notExpected); // B: Correctly fails (Expected value 3,14 to be between 1 and 1, but it was not.)
        }
        [Test]
        public void TestNullableFloatEquality()
        {
            float expected = 3.14f;
            float notExpected = 1.0f;
            float? actual = 3.14f;
            actual.Should().BeApproximately(expected, 0.1f);
            actual.Should().BeApproximately(notExpected, 0.1f); // C: Passes (I expected it to fail!)
            actual.Should().BeInRange(expected, expected);
            actual.Should().BeInRange(notExpected, notExpected); // D: Correctly fails (Expected value 3,14 to be between 1 and 1, but it was not.)
        }
    }
}

正如您从我的评论中看到的那样,TestFloatEquality() AB 都正确失败(只需注释掉第一个失败的测试即可进入第二个测试)。

然而,在TestNullableFloatEquality()中,D通过,但C失败。我本以为C在这里也会失败。只是为了提到它,如果我使用 NUnit 添加断言:

Assert.AreEqual(expected, actual); // Passes
Assert.AreEqual(notExpected, actual); // Fails (Expected: 1.0f But was:  3.1400001f)

这些按预期通过和失败。

所以,对于一个问题:这是FluentAssertions中的一个错误,还是我在可空比较方面遗漏了一些东西?

在使用 FluentAssertions 将可为空的类型与其基础类型进行比较时,这是一个错误吗?

这是一个

错误。我在 1.7.x 发布分支和主干中都修复了这个问题。新 2.0.0 的开发仍在进行中,因此我们最终可能会决定发布 1.7.2。

有关确切状态,请参阅 http://fluentassertions.codeplex.com/workitem/12199。