[C#FluentAssertions在断言失败后继续

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[C#FluentAssertions在断言失败后继续相关的知识,希望对你有一定的参考价值。

在FluentAssertions中断言失败后是否可以继续?我有一些断言,没有断言,只能报告,但不能使测试失败。

[TestClass]
public class UnitTest1

    [TestMethod]
    public void TestMethod1()
    
        using (var scope = new AssertionScope())
        
            "This Should not Failed with an AssertException".Should().Be("Should Failed");
            "And this also not".Should().Be("Should Failed");
            "All should only be printed to the console".Should().NotBeEmpty();
        
        "But the Test should continue".Should().Be("And Failed here with an AssertException");
    

答案

您可以将断言包装在AssertionScope中,以在单个异常中捕获所有失败。另请参见https://fluentassertions.com/introduction#assertion-scopes

另一答案

对于输出端,请使用XUnit中的ITestOutputHelper-这是在XUnit 2.0+中获取测试日志输出的唯一方法。如果必须将检查写为断言,则可以将自己的IAssertionStrategy实现作为构造函数参数提供给AssertionScope,并让其将断言失败消息发送到XUnit的测试输出,而不是抛出。

注意:您至少需要v5.9.0的FluentAssertions才能实现此目的。

public class XUnitTestOutputAssertionStrategy : IAssertionStrategy

    private readonly ITestOutputHelper output;
    private readonly List<string> failures = new List<string>();

    public XUnitTestOutputAssertionStrategy(ITestOutputHelper output)
    
        this.output = output;
    

    public void HandleFailure(string message)
    
        failures.Add(message);
    

    public IEnumerable<string> DiscardFailures()
    
        var snapshot = failures.ToArray();
        failures.Clear();
        return snapshot;
    

    public void ThrowIfAny(IDictionary<string, object> context)
    
        if (!failures.Any()) return;

        var sb = new StringBuilder();
        sb.AppendLine(string.Join(Environment.NewLine, failures));
        foreach ((string key, object value) in context)
            sb.AppendFormat("\nWith 0:\n1", key, value);

        output.WriteLine(sb.ToString());
    

    public IEnumerable<string> FailureMessages => failures;


public class ContrivedTests

    private readonly ITestOutputHelper output;

    public ContrivedTests(ITestOutputHelper output)
    
        this.output = output;
    

    [Fact]
    public void WhenRunningTest_WithContrivedExample_ShouldOutputThenAssert()
    
        using (new AssertionScope(new XUnitTestOutputAssertionStrategy(output)))
        
            "Failures will log".Should().Contain("nope", "because we want to log this");
            "Success won't log".Should().StartWith("Success", "because we want to log this too, but it succeeded");
        

        "This line will fail the test".Should().StartWith("Bottom Text", "because I pulled a sneaky on ya");
    

以上是关于[C#FluentAssertions在断言失败后继续的主要内容,如果未能解决你的问题,请参考以下文章

使用 Fluent Assertions 库的多个断言

如何在 FluentAssertions 的集合断言中重用自定义对象断言

流利的断言 - 如何在类型检查后正确链接

C# fluent 断言检查结果为 bool

如何使用 FluentAssertions 4.x 版断言异常?

FluentAssertions 断言单个对象的多个属性