【问题标题】:How to show the variable name on the exception message when the assertion fails using FluentAssertions?使用 FluentAssertions 断言失败时如何在异常消息中显示变量名?
【发布时间】:2020-05-31 20:26:24
【问题描述】:

我正在尝试使用 FluentAssertions 库创建一些断言类。这是断言代码:

public AndConstraint<MyTaskAssertions> Work(string because = "", params object[] becauseArgs)
{
    Execute.Assertion
        .BecauseOf(because, becauseArgs)
        .WithExpectation("Expected {context:mytask} to work{reason}, ")
        .Given(() => Subject)
        .ForCondition(x => x.Works)
        .FailWith("but it doesn't");

    return new AndConstraint<MyTaskAssertions>(this);
}

这是我的测试:

var t = new MyTask {Works=false};
t.Should().Work();

一切正常,除了变量名t,“mytask”显示在异常消息上:

预计 mytask 可以工作,但它没有

我已经阅读了文档上的Extensibility 页面,并且我还检查了内置断言的源代码,但我仍然不确定异常消息究竟缺少什么来显示实际变量名称而不是“上下文:”占位符之后的内容。

【问题讨论】:

    标签: fluent-assertions


    【解决方案1】:

    您需要用[CustomAssertion] 标记您的方法。另见https://fluentassertions.com/introduction#subject-identification

    【讨论】:

    猜你喜欢
    • 2016-12-22
    • 2020-02-21
    • 2021-10-27
    • 2018-09-26
    • 2020-04-08
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多