如何解决提供对 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(或其他合适的类),使我的 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);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。