簡體   English   中英

C# FluentAssertions 在斷言失敗后繼續

[英]C# FluentAssertions continue after Failed Assertion

在 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

對於輸出端,使用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}:\n{1}", 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");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM