c# - 提供 FluentAssertions 的扩展

标签 c# unit-testing fluent-assertions

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

相关文章:

c# - 输出所有命令行参数

c# - 在属性内执行初始化是一种好习惯吗?

unit-testing - Scala 单元测试

java - 使用 Mockito 验证是否使用包含子字符串的参数调用了方法

Python Mock - 如何像普通方法一样返回 MagicMock

c# - 如何创建自定义 FluentAssertion 错误消息?

c# - Active Directory 不适用于异地

c# - 遍历 Entity Framework 父子关系的通用方法

c# - FluentAssertions 检查对象字段是否不相等?

ShouldBeEquivalentTo 的 C# Fluent Assertions 全局选项