Emm*_*RIN 5 c# unit-testing fluent-assertions
因为我有一些角度,所以我想检查角度模数 360\xc2\xb0:
\n double angle = 0;\n double expectedAngle = 360;\n angle.Should().BeApproximatelyModulus360(expectedAngle, 0.01);\nRun Code Online (Sandbox Code Playgroud)\n我已经按照教程编写了 Fluent Assertions 框架的扩展:https ://fluentassertions.com/extensibility/
\npublic static class DoubleExtensions\n{\n public static DoubleAssertions Should(this double d)\n {\n return new DoubleAssertions(d);\n }\n}\n\n\npublic class DoubleAssertions : NumericAssertions<double>\n{\n public DoubleAssertions(double d) : base(d)\n {\n }\n public AndConstraint<DoubleAssertions> BeApproximatelyModulus360(\n double targetValue, double precision, string because = "", params object[] becauseArgs)\n {\n Execute.Assertion\n .Given(() => Subject)\n .ForCondition(v => MathHelper.AreCloseEnoughModulus360(targetValue, (double)v, precision))\n .FailWith($"Expected value {Subject}] should be approximatively {targetValue} with {precision} modulus 360");\n return new AndConstraint<DoubleAssertions>(this);\n}\nRun Code Online (Sandbox Code Playgroud)\n当我使用这两个命名空间时:
\nusing FluentAssertions;\nusing MyProjectAssertions;\nRun Code Online (Sandbox Code Playgroud)\n因为我也使用:
\n aDouble.Should().BeApproximately(1, 0.001);\nRun Code Online (Sandbox Code Playgroud)\n我收到以下编译错误:\nAmbiguous call between \'FluentAssertions.AssertionExtensions.Should(double)\' and \'MyProjectAssertions.DoubleExtensions.Should(double)\'
如何更改我的代码以扩展标准 NumericAssertions (或其他合适的类)以使我的BeApproximatelyModulus360下一个符合标准BeApproximately?
谢谢
\n如果您想直接访问对象上的扩展方法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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以一起使用它们。
public class Test
{
public Test()
{
double aDouble = 4;
aDouble.Should().BeApproximately(1, 0.001);
aDouble.Should().BeApproximatelyModulus360(0, 0.1);
}
}
Run Code Online (Sandbox Code Playgroud)