当我遇到一个测试失败时,我正在为实用程序库编写一些单元测试,该测试实际上通过了。这个问题与比较两个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.)
}
}
}
正如您从我的评论中看到的那样,A和BTestFloatEquality()
都正确失败(只需注释掉第一个失败的测试即可进入第二个)。
然而TestNullableFloatEquality()
,D通过但C失败。我本来预计C也会在这里失败。顺便提一下,如果我使用 NUnit 添加断言:
Assert.AreEqual(expected, actual); // Passes
Assert.AreEqual(notExpected, actual); // Fails (Expected: 1.0f But was: 3.1400001f)
那些按预期通过和失败。
所以,对于这个问题:这是 FluentAssertions 中的一个错误,还是我错过了可空比较方面的一些东西?