【问题标题】:Output additional information when tests fail测试失败时输出附加信息
【发布时间】:2018-11-15 16:38:22
【问题描述】:

我的一个包含Assert.Equal(2, list.Count); 的测试在持续集成服务器 Appveyor 上失败,但我无法在本地机器上重现该故障。

我希望从错误信息中得到更多信息,但不知道该怎么做。

xUnit.net 的作者坚持他们不应该允许用户指定自定义错误消息,请参阅https://github.com/xunit/xunit/issues/350。这就是为什么没有 API 允许我编写例如。 Assert.Equal(2, list.Count, "The content of the list is " + ...);

我还研究了 Fluent Assertions。如果我写list.Should().HaveCount(3, "the content of the list is " + ...);,则输出为

预计集合包含 3 个项目,因为列表的内容是
...,但找到了 2 个。

“因为”从句在英语语法中没有意义。因为参数似乎用于描述预期行为,而不是实际行为。

考虑到 xUnit.net 和 Fluent Assertions 都阻止我们提供有关失败的额外信息,当测试失败时输出额外信息是调试远程错误的好方法吗?

输出附加信息的最佳方式是什么?

【问题讨论】:

  • 如果您在测试中只断言一件事 - 测试名称可以更具描述性:Should merge two wildcards

标签: unit-testing continuous-integration xunit fluent-assertions


【解决方案1】:

如果您想查看列表的实际内容以进行调试,并且您正在使用 Fluent Assertions,您可以这样做:

using (new AssertionScope(Formatter.ToString(list)) { list.Should().HaveCount(3); }

断言作用域会将消息的collection 部分替换为其他内容。这不是很好,但会工作。

或者,您可以像这样利用because 参数:

list.Should().HaveCount(3, "because I expected list {0} to contain that many items", list);

FA 将格式化中的每个占位符,因为短语使用相同的Formatter.String

【讨论】:

    猜你喜欢
    • 2019-08-29
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2012-01-01
    • 2014-10-22
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    相关资源
    最近更新 更多