【发布时间】:2020-03-30 06:06:06
【问题描述】:
是否有可能覆盖FluentAssertions 的默认消息。有时我只想打印我的自定义消息作为测试失败的结果。到目前为止,我还没有找到任何解决方案,但也许我错过了一些东西。
例子:
myOrderedList.SequenceEqual(desiredOrderedList)
.Should().BeTrue("Elements are not in correct order.\r\n" +
$"Error in JSON file: {fileName}.\r\n" +
$"Required order of elements is {string.Join(", ", desiredOrderedList)}");
结果消息是:
Expected boolean to be true because Elements are not in correct order.
Error in JSON file: MyTestData.json.
Required order of elements is str1, str2, str3, but found False.
但我只想拥有这个
Elements are not in correct order.
Error in JSON file: MyTestData.json.
Required order of elements is str1, str2, str3.
编辑: 试过这个
public static class BooleanAssertionsExtensions
{
public static BooleanAssertions Should(this bool? instance)
{
return new BooleanAssertions(instance);
}
}
public class BooleanAssertions
{
public BooleanAssertions(bool? instance)
{
Subject = instance;
}
public bool? Subject { get; private set; }
public AndConstraint<BooleanAssertions> BeTrueCustom(string because = "", params object[] becauseArgs)
{
Execute.Assertion
.ForCondition(Subject == true)
.BecauseOf(because, becauseArgs)
.FailWith("{reason}");
return new AndConstraint<BooleanAssertions>(this);
}
}
但是在尝试执行.Should().BeTrueCustom(... 时,我收到此错误:“BooleanAssertions”不包含“BeTrueCustom”的定义,并且找不到接受“BooleanAssertions”类型的第一个参数的可访问扩展方法“BeTrueCustom”(是您缺少 using 指令或程序集引用?
我可能有点慢,但不明白我做错了什么,或者我如何创建新的扩展来扩展或覆盖默认行为(默认消息)。很遗憾 FA 不支持这种基本的东西。
【问题讨论】:
-
myOrderedList.Should().BeEquivalentTo(desiredOrderedList, config => config.WithStrictOrdering())呢? -
@Fabio 仍然没有解决消息问题。我只想像其他工具一样打印我的自定义消息。 Dennis 可能知道除非我创建自己的实现,否则这是不可能的——他创建了 FluentAssertions。然而这并不容易,现在我什至不知道如何创建自己的 impl。 BeEquivalentTo 将打印
Expected collection {SomeProperty: 1, OtherProperty: item, SomeProperty: 2, OtherProperty: item} to be equivalent to {SomeProperty: 1, OtherProperty: item, SomeProperty: 2, OtherProperty: other}, but it misses {SomeProperty: 2, OtherProperty: other}. -
@Fabio 没有注意到 config.很好。但是,如果还使用自定义消息,那将是一团糟,这就是为什么我不喜欢 FA 使用这些自定义消息的方式。您需要严格遵循
Excepted something {because message} but found smthing other.的上下文 无法有意义地添加一些重要消息,因为它已插入该 FA 消息上下文中。
标签: c# unit-testing xunit fluent-assertions