在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");
}
}发布于 2019-12-21 02:18:42
对于输出端,使用XUnit中的ITestOutputHelper -这是在XUnit 2.0+中获得测试日志输出的唯一方法。如果必须将检查作为断言编写,可以将自己的IAssertionStrategy实现作为构造函数参数提供给AssertionScope,并让它将断言失败消息发送到XUnit的测试输出,而不是抛出异常。
注意:要做到这一点,你至少需要FluentAssertions的v5.9.0。
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");
}
}发布于 2019-12-16 16:27:16
您可以将断言包装在AssertionScope中,以在单个异常中捕获所有故障。另请参阅https://fluentassertions.com/introduction#assertion-scopes
https://stackoverflow.com/questions/59352738
复制相似问题