FluentAssertions自定义Double比较器失效问题求助
问题分析与解决方案
你的测试失败原因是FluentAssertions的Using<T>回调并不接收布尔返回值来判断断言结果,它需要你在回调内部主动触发断言失败逻辑。你当前的代码只是调用了HasMinimalDifference但没有处理返回值,FluentAssertions会忽略这个调用,继续使用默认的double相等性校验,导致测试不通过。
修复方案1:调整Using<T>回调逻辑
修改DoubleTest方法,在自定义比较失败时调用FailWith抛出断言失败信息:
[TestMethod] public void DoubleTest() { double temp1 = 0.1 - 0.025; double temp2 = 0.075; temp1.ShouldBeEquivalentTo(temp2, options => options .Using<double>(a => { if (!a.Subject.HasMinimalDifference(a.Expectation, 1)) { a.FailWith($"Expected {{context:double}} to have minimal difference with {a.Expectation}, but found {a.Subject}"); } }) .WhenTypeIs<double>()); }
修复方案2:自定义可扩展的FluentAssertions断言方法
如果需要未来扩展比较逻辑,推荐封装成自定义的FluentAssertions扩展方法,这样复用性更强:
public static class DoubleAssertionsExtensions { public static AndConstraint<DoubleAssertions> HaveMinimalDifference(this DoubleAssertions assertions, double expectation, int units, string because = "", params object[] becauseArgs) { Execute.Assertion .ForCondition(assertions.Subject.HasMinimalDifference(expectation, units)) .BecauseOf(because, becauseArgs) .FailWith($"Expected {{context:double}} to have minimal difference (within {units} units) with {expectation}, but found {assertions.Subject}"); return new AndConstraint<DoubleAssertions>(assertions); } }
然后测试代码可以简化为:
[TestMethod] public void DoubleTest() { double temp1 = 0.1 - 0.025; double temp2 = 0.075; temp1.Should().HaveMinimalDifference(temp2, 1); }
这种方式更符合FluentAssertions的语法风格,也方便后续对HasMinimalDifference方法进行扩展(比如调整单位逻辑、增加参数等)。
补充说明
你的HasMinimalDifference方法本身逻辑是正确的(基于IEEE 754双精度浮点数的二进制位差比较),问题仅在于FluentAssertions的回调使用方式错误。
内容的提问来源于stack exchange,提问作者ProtonFisher
相关产品推荐
相关产品推荐

