【问题标题】:Any possibility to override default FluentAsserions message?是否有可能覆盖默认的 FluentAsserions 消息?
【发布时间】: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 =&gt; 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


【解决方案1】:

除非您编写自己的扩展程序,否则您不能。

【讨论】:

  • 嗯这实际上是什么意思?我有点困惑。不想做新的扩展,只想覆盖当前的功能。对我来说,除去 {reason} 之外的每个 .FailWith() 中的全部内容就足够了。或者更好的是,添加简单的 boolean OnlyCustomMessage=false 作为参数,当只有 {reason} 出现在 FailWith() 中时 if 为 true
  • 请检查我的问题中的 EDIT,不知道我做错了什么
  • 编译器可能会根据重载解析规则选择不同的扩展方法。检查编译器选择的Should() 方法的定义以了解发生了什么。
猜你喜欢
  • 2020-01-17
  • 2014-03-05
  • 2014-04-04
  • 1970-01-01
  • 2011-02-25
  • 1970-01-01
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多