【发布时间】:2012-05-31 21:52:54
【问题描述】:
我正在为实用程序库编写一些单元测试时,遇到了一个我预计会失败但实际上已通过的测试。该问题与比较两个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.)
}
}
}
正如您从我的 cmets 中看到的那样,在 TestFloatEquality() 中,A 和 B 都正确失败(只需注释掉第一个失败的测试即可进入第二个) .
然而,在TestNullableFloatEquality() 中,D 通过但 C 失败。我本来预计 C 也会在这里失败。顺便提一下,如果我使用 NUnit 添加断言:
Assert.AreEqual(expected, actual); // Passes
Assert.AreEqual(notExpected, actual); // Fails (Expected: 1.0f But was: 3.1400001f)
按预期通过和失败。
那么,对于这个问题:这是 FluentAssertions 中的一个错误,还是我在可空比较方面遗漏了什么?
【问题讨论】:
标签: c# comparison nunit nullable fluent-assertions