【问题标题】:Fluent assertions: Assert one OR another value流畅的断言:断言一个或另一个值
【发布时间】:2014-10-21 22:11:25
【问题描述】:

使用流利的断言,我想断言给定的字符串包含两个字符串之一:

actual.Should().Contain("oneWay").Or().Should().Contain("anotherWay"); 
// eiter value should pass the assertion.
// for example: "you may do it oneWay." should pass, but
// "you may do it thisWay." should not pass

只有两个值都不包含时,断言才会失败。这不起作用(甚至无法编译),因为没有 Or() 运算符。

这就是我现在的做法:

bool isVariant1 = actual.Contains(@"oneWay");
bool isVariant2 = actual.Contains(@"anotherWay");
bool anyVariant = (isVariant1 || isVariant2);
anyVariant.Should().BeTrue("because blahblah. Actual content was: " + actual);

这很冗长,必须手动创建“因为”参数才能获得有意义的输出。

有没有办法以更易读的方式做到这一点?解决方案也应该适用于其他流畅的断言类型,如Be()HaveCount() 等...

我在 .NET 3.5 上使用 FluentAssertions 版本 2.2.0.0,如果这很重要的话。

【问题讨论】:

    标签: c# unit-testing combinations assert fluent-assertions


    【解决方案1】:

    您可以通过编写一个简单的字符串扩展使其更具可读性:

    public static class StringExt
    {
        public static bool ContainsAnyOf(this string self, params string[] strings)
        {
            return strings.Any(self.Contains);
        }
    }
    

    那么你可以这样做:

    actual.ContainsAnyOf("oneWay", "anotherWay").Should().BeTrue("because of this reason");
    

    不幸的是,这对信息的“原因”部分没有帮助,但我认为这要好一些。

    【讨论】:

    • 实际上,当这失败时,你不知道出了什么问题。
    【解决方案2】:

    我会将它作为字符串断言的扩展。像这样的:

    public static void BeAnyOf(this StringAssertions assertions, string[] expectations, string because, params string[] args) {
        Execute.Assertion
               .ForCondition(expectations.Any(assertions.Subject.Contains))
               .BecauseOf(because, args)
               .FailWith("Expected {context:string} to be any of {0}{reason}", expectations);
    }
    

    您甚至可以分叉 repository 并向我提供 Pull Request 以使其成为下一个版本的一部分。

    【讨论】:

    • 这个怎么用?这错过了很多解释!如果我能创建类似这样的东西那就太好了:actual.Should().ContainAnyOf("oneWay", "another way"); 这将与现有方式一致。
    • 它允许您拨打actual.Should().BeAnyOf("oneWay", "another way");
    • @DennisDomen 我如何为 Enums 实现相同的方法?
    【解决方案3】:

    这不应该有效吗?

    actual.Should().BeOneOf("oneWay", "anotherWay");
    

    使用 v3.1.229 为我工作。

    【讨论】:

    • 不适合我,因为我不想断言整个字符串内容,而只是实际值部分包含其中一个值。
    猜你喜欢
    • 2010-09-23
    • 2013-04-16
    • 2011-10-05
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 2018-02-25
    相关资源
    最近更新 更多