【问题标题】:How can I compare null and string.Empty (or "") in fluent assertions?如何在流利的断言中比较 null 和 string.Empty(或“”)?
【发布时间】:2014-07-24 21:28:43
【问题描述】:

我有两个相同类型的对象,该类型有一个字符串字段,在第一个对象中值为空,在第二个对象中值为“”,我如何强制流畅的断言假设这是正确的?

断言本身:

callResult.ShouldBeEquivalentTo(centreResponse, 
                                opt => opt.Excluding(r => r.DateOpen));

这里抛出异常,说明期望值为null,真实值为""(反之亦然)

【问题讨论】:

  • 对象是什么类型?我可以假设中心响应是一个字符串,而 opt 是 string[] 还是什么?
  • 为什么要将null 和空字符串视为等效?这不是一个好主意。
  • 对象是 CentreResponse 类型,它是一个复杂类型,关于比较规则 - 这是要求,它们来自不同的数据源,但在这个特定的上下文中 null 和空字符串是相等的
  • 加上field,你的意思是C#字段吗?
  • 我的意思是一个字符串类型的属性,抱歉误导:)

标签: c# integration-testing fluent-assertions


【解决方案1】:

您可以做的是像这样覆盖string 类型的属性的行为:

callResult.ShouldBeEquivalentTo(centreResponse, opt => opt
          .Excluding(r => r.DateOpen)
          .Using<string>(ctx => CompareStrings(ctx)).WhenTypeIs<string>());       

public void CompareStrings(IAssertionContext<string> ctx)
{
    var equal = (ctx.Subject ?? string.Empty).Equals(ctx.Expectation ?? string.Empty);

    Execute.Assertion
        .BecauseOf(ctx.Because, ctx.BecauseArgs)
        .ForCondition(equal)
        .FailWith("Expected {context:string} to be {0}{reason}, but found {1}", ctx.Subject, ctx.Expectation);
}    

您可以通过将CompareStrings 方法封装在IAssertionRule 的实现中来稍微清理一下。请参阅 FluentAssertions here 的单元测试中的 RelaxingDateTimeAssertionRule

您可以将该自定义断言规则添加为您的 callResult 变量类型的所有断言的默认值,但我仍然需要添加一些内容以允许全局默认值。

【讨论】:

    猜你喜欢
    • 2017-09-20
    • 2013-03-08
    • 2016-10-19
    • 2020-02-18
    • 2013-06-07
    • 2019-12-14
    • 2014-02-13
    • 2016-10-27
    • 2021-01-08
    相关资源
    最近更新 更多