提供对FluentAssertions的扩展



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

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

我已经为流畅断言框架写了一个扩展下面的教程: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(或其他合适的类)有我的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);
}
}

相关内容

  • 没有找到相关文章

最新更新