gpt4 book ai didi

c# - FluentAssertions WhenType 是 double.NaN

转载 作者:行者123 更新时间:2023-11-30 16:05:23 25 4
gpt4 key购买 nike

我有两个复杂的对象,里面有不同的类型(对象、字符串、 double 等)。我想使用以下代码比较它们:

myActualObject.ShouldBeEquivalentTo(myExpectedObject, options => options
.Using<double>(dbl => dbl.Subject.Should().BeApproximately(dbl.Expectation,
ABS_ERROR))
.WhenTypeIs<double>()
);

我正在尝试使用 .BeApproximately 行为来比较 double 类型的属性值,但由于一种特殊情况而无法正常工作:

  • 有时我在 double 中有一个 double.NaN,将一个 NaN 与另一个 NaN 进行比较会导致断言失败(因为 BeApproximately 行为)。在这种情况下,我如何才能跳过比较,或使其为真?

  • 最后,如何打印导致断言失败的对象的名称?

提前致谢。

编辑>>>>

我找到了第一种方法(感谢@Sam Holder):

myActualObject.ShouldBeEquivalentTo(myExpectedObject, options => options
.Using<double>(ctx => CompareDoubleApprox(ctx, myExpectedObject.Name))
.WhenTypeIs<double>()
);

...

public void CompareDoubleApprox(IAssertionContext<double> ctx, string Scope)
{
bool IsDoubleOrInfinite = (double.IsNaN(ctx.Expectation) || double.IsInfinity(ctx.Expectation));
bool absoluteErrorOK = Math.Abs(ctx.Subject - ctx.Expectation) < ABS_ERROR;

Execute.Assertion
.BecauseOf(ctx.Reason, ctx.ReasonArgs)
.ForCondition(IsDoubleOrInfinite || absoluteErrorOK)
.FailWith("{3}: Expected {context:double} to be {0} +/- {1} {reason}, but found {2}", ctx.Subject, ABS_ERROR, ctx.Expectation, Scope);
}

我的断言转储看起来像:

"MyObjectName": Expected member Foo.Bar to be 0 +/- 1E-05 , but found 1,39675

"MyObjectName": Expected member Foo.FooBar to be 2,07781 +/- 1E-05 , but found 2,98412

...More assertion fails...

我希望它在打印所有失败之前仅打印一次 objectName。

更新>>>>>

我想要的行为在github上还没有实现:https://github.com/dennisdoomen/fluentassertions/issues/310 .被标记为增强。感谢您的帮助。

最佳答案

未经测试的暗杀,但可能像这样工作:

myActualObject.ShouldBeEquivalentTo(myExpectedObject, options => options
.Using<double>(dbl =>
{
if (!double.IsNaN(dbl.Subject))
{
String errorMessage = string.Format("{0} caused the assertion to fail",myExpectedObject);
dbl.Subject.Should().BeApproximately(dbl.Expectation, ABS_ERROR, errorMessage);
}
})
.WhenTypeIs<double>()
);

关于c# - FluentAssertions WhenType 是 double.NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33671908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com