c# - 流利的断言:大致比较字典值
问题描述
我再一次难以让 FluentAssertions 的可定制方面Should().BeEquivalentTo
来做我所追求的。当前的问题是近似比较字典值。我将如何使用以下BeEquivalentTo
选项通过此测试:
[Fact]
public void SomeTest()
{
var dictOne = new Dictionary<string, double>
{
{ "a", 1.2345 },
{ "b", 2.4567 },
{ "c", 5.6789 },
{ "s", 3.333 }
};
var dictTwo = new Dictionary<string, double>
{
{ "a", 1.2348 },
{ "b", 2.4561 },
{ "c", 5.679 },
{ "s", 3.333 }
};
dictOne.Should().BeEquivalentTo(dictTwo, options => options
.Using<double>(ctx => ctx.ApproximatelyCompareDouble(1e-2))
.WhenTypeIs<KeyValuePair<string, double>>()
);
}
ApproximatelyCompareDouble
工作正常,但我已将其包含在此处以完成:
public static void ApproximatelyCompareDouble(this IAssertionContext<double> ctx, double precision)
{
var bothNaN = double.IsNaN(ctx.Subject) && double.IsNaN(ctx.Expectation);
var bothPositiveInf = double.IsPositiveInfinity(ctx.Subject) && double.IsPositiveInfinity(ctx.Expectation);
var bothNegativeInf = double.IsNegativeInfinity(ctx.Subject) && double.IsNegativeInfinity(ctx.Expectation);
var withinPrecision = Math.Abs(ctx.Subject - ctx.Expectation) <= precision;
Execute.Assertion
.BecauseOf(ctx.Because, ctx.BecauseArgs)
.ForCondition(bothNaN || bothPositiveInf || bothNegativeInf || withinPrecision)
.FailWith("Expected {context:double} to be {0} +/- {1} {reason}, but found {2}", ctx.Subject, precision, ctx.Expectation);
}
解决方案
推荐阅读
- python - 如何提高 Pytesseract 提取数字的准确性
- excel - VBA中的名称和全名有什么区别?
- git - 如何压缩给定提交后所做的更改?(混帐存档)
- aspnetboilerplate - 是否有任何代码生成器(内置或第三方)可用于为 ASP..NET 样板生成数据库优先代码?
- python - 在数据边界处寻找峰值
- reactjs - undefined 不是 React Native 中的函数
- javascript - 将数组合并为一个
- php - jQuery/PHP 文件上传在 99% 处重新启动,然后返回超时
- python - 没有语法错误的python代码中出现运行时错误
- javascript - “$.ajax 不是函数”,但前提是调用放在函数内部