提供 FluentAssertions 的扩展

Providing an extension to FluentAssertions

因为我有一些角度,所以我想检查角度模数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);

我得到以下编译错误: Ambiguous call between 'FluentAssertions.AssertionExtensions.Should(double)' and 'MyProjectAssertions.DoubleExtensions.Should(double)'

如何更改我的代码以扩展标准 NumericAssertions(或其他合适的 class)以使我的 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);

        }
    }