gpt4 book ai didi

c# - 提供 FluentAssertions 的扩展

转载 作者:行者123 更新时间:2023-12-01 23:30:30 31 4
gpt4 key购买 nike

因为我有一些角度,所以我想检查角度模数 360°:

    double angle = 0;
double expectedAngle = 360;
angle.Should().BeApproximatelyModulus360(expectedAngle, 0.01);

我已经编写了 Fluent Assertions 框架的扩展遵循教程:https://fluentassertions.com/extensibility/

public static class DoubleExtensions
{
public static DoubleAssertions Should(this double d)
{
return new DoubleAssertions(d);
}
}


public class DoubleAssertions : NumericAssertions<double>
{
public DoubleAssertions(double d) : base(d)
{
}
public AndConstraint<DoubleAssertions> BeApproximatelyModulus360(
double targetValue, double precision, string because = "", params object[] becauseArgs)
{
Execute.Assertion
.Given(() => Subject)
.ForCondition(v => MathHelper.AreCloseEnoughModulus360(targetValue, (double)v, precision))
.FailWith($"Expected value {Subject}] should be approximatively {targetValue} with {precision} modulus 360");
return new AndConstraint<DoubleAssertions>(this);
}

当我同时使用两个命名空间时:

using FluentAssertions;
using MyProjectAssertions;

因为我也用过:

 aDouble.Should().BeApproximately(1, 0.001);

我得到以下编译错误:“FluentAssertions.AssertionExtensions.Should(double)”和“MyProjectAssertions.DoubleExtensions.Should(double)”之间的调用不明确

如何更改我的代码以扩展标准 NumericAssertions(或其他合适的类)以使我的 BeApproximatelyModulus360 位于标准 BeApproximately 旁边?

谢谢

最佳答案

如果你想直接访问 double 上的扩展方法对象,而不是 DoubleAssertion对象,为什么引入甚至创建新类型的复杂性 DoubleAssertion .相反,直接为 NumericAssertions<double> 定义一个扩展方法.

  public static class DoubleAssertionsExtensions
{
public static AndConstraint<NumericAssertions<double>> BeApproximatelyModulus360(this NumericAssertions<double> parent,
double targetValue, double precision, string because = "", params object[] becauseArgs)
{
Execute.Assertion
.Given(() => parent.Subject)
.ForCondition(v => MathHelper.AreCloseEnoughModulus360(targetValue, (double)v, precision))
.FailWith(
$"Expected value {parent.Subject}] should be approximatively {targetValue} with {precision} modulus 360");
return new AndConstraint<NumericAssertions<double>>(parent);
}
}

然后您可以一起使用它们。

 public class Test
{
public Test()
{
double aDouble = 4;

aDouble.Should().BeApproximately(1, 0.001);
aDouble.Should().BeApproximatelyModulus360(0, 0.1);

}
}

关于c# - 提供 FluentAssertions 的扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66358810/

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