[有一个官方示例,如何在FluentAssertions docs创建CustomAssertion,但是我尝试应用它失败。这是代码:
public abstract class BaseTest
{
public List<int> TestList = new List<int>() { 1, 2, 3 };
}
public class Test : BaseTest { }
public class TestAssertions
{
private readonly BaseTest test;
public TestAssertions(BaseTest test)
{
this.test = test;
}
[CustomAssertion]
public void BeWorking(string because = "", params object[] becauseArgs)
{
foreach (int num in test.TestList)
{
num.Should().BeGreaterThan(0, because, becauseArgs);
}
}
}
public class CustomTest
{
[Fact]
public void TryMe()
{
Test test = new Test();
test.Should().BeWorking(); // error here
}
}
我遇到编译错误:
CS1061 'ObjectAssertions' does not contain a definition for 'BeWorking' and no accessible extension method 'BeWorking' accepting a first argument of type 'ObjectAssertions' could be found (are you missing a using directive or an assembly reference?)
我也尝试将BeWorking
从TestAssertions
移至BaseTest
,但仍然无法正常工作。我缺少什么,如何使它工作?
您实际上做得很好:)您缺少的最重要的东西是扩展类。我会引导您完成。
添加此类:
public static class TestAssertionExtensions
{
public static TestAssertions Should(this BaseTest instance)
{
return new TestAssertions(instance);
}
}
像这样修复您的TestAssertions类:
public class TestAssertions : ReferenceTypeAssertions<BaseTest, TestAssertions>
{
public TestAssertions(BaseTest instance) => Subject = instance;
protected override string Identifier => "TestAssertion";
[CustomAssertion]
public AndConstraint<TestAssertions> BeWorking(string because = "", params object[] becauseArgs)
{
foreach (int num in Subject.TestList)
{
num.Should().BeGreaterThan(0, because, becauseArgs);
}
return new AndConstraint<TestAssertions>(this);
}
}
您的TryMe()测试现在应该可以正常工作。祝你好运。