Using fluent assertions, I would like to assert that a given string contains either one of two strings:
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
Only if neither of the values is contained, the assertion should fail. This does NOT work (not even compile) as there is no Or()
operator.
This is how I do it now:
bool isVariant1 = actual.Contains(@"oneWay");
bool isVariant2 = actual.Contains(@"anotherWay");
bool anyVariant = (isVariant1 || isVariant2);
anyVariant.Should().BeTrue("because blahblah. Actual content was: " + actual);
This is verbose, and the "because" argument must get created manually to have a meaningful output.
Is there a way to do this in a more readable manner? A solution should also apply to other fluent assertion types, like Be()
, HaveCount()
etc...
I am using FluentAssertions version 2.2.0.0 on .NET 3.5, if that matters.
Fluent Assertions are important in unit testing because they allow the code to be easily read and followed. This makes it easier to determine whether or not an assertion is being met. As a result, everyone can easier read and understand unit tests, making it easier to locate the failing assert.
Fluent Assertions is a set of . NET extension methods that allow you to more naturally specify the expected outcome of a TDD or BDD-style unit test.
Assertion Scopes make our lives easier when using multiple assertions within our unit tests by saving us time and effort when finding out why our tests are failing. Assertion Scopes allow us to test multiple assertions within a single test execution.
I would make it an extension to the string assertions. Something like this:
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);
}
You could even fork the repository and provide me with a Pull Request to make it part of the next version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With