Fluent断言:断言一个或另一个值

Mar*_*cel 11 c# combinations unit-testing assert fluent-assertions

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

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
Run Code Online (Sandbox Code Playgroud)

仅当包含这两个值时,断言才会失败.由于没有Or()运算符,这不起作用(甚至不编译).

这是我现在这样做的方式:

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

这很冗长,必须手动创建"因为"参数以获得有意义的输出.

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

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

Den*_*men 11

我会把它作为字符串断言的扩展.像这样的东西:

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);
}
Run Code Online (Sandbox Code Playgroud)

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


bpf*_*ich 10

这不应该工作吗?

actual.Should().BeOneOf("oneWay", "anotherWay");
Run Code Online (Sandbox Code Playgroud)

使用v3.1.229为我工作.