3

Is it possible to force fluent assertions to pass Should().Be() for comparison between null and empty string? Or maybe this can be done somehow with BeEquivalentTo?

Example:

text1.Should().Be(text2);

I want code above to pass when:

  • text1 will be 'foo' and text2 will be 'foo' (just standard behavior)
  • text1 will be empty string, text2 will be null

So I need to make assertion that can compare strings, but if one of them is empty and other is null it should still pass.

Some context:

I need it to for my selenium autotests. I'm having some Dto which I send to api to create a product table as test preconditions (some fields of Dto CAN be null). Then in UI of an application this null is presented as empty string. Later in test I'm checking if each column present correct data and I want to be able to make fluent assertions pass assertion between empty string and null (and of course still pass if two proper strings are compared -> when none of Dto field was null).

user14789187
  • 31
  • 1
  • 3
  • Does this answer your question? [Fluent assertion for OR condition](https://stackoverflow.com/questions/34654341/fluent-assertion-for-or-condition) – quaabaam Dec 08 '20 at 19:40

2 Answers2

1

You can use AssertionScope:

string text1 = "";
string text2 = null;
using (new AssertionScope())
{
    test1.Should().BeOneOf("foo", null, "");
    test2.Should().BeOneOf("foo", null, "");
};
Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
coder_b
  • 827
  • 6
  • 15
  • As I said this fields of Dto 'can' be null, but for most ot the time I will them with strings. If I will fill all fields of Dto, then in UI I will see proper string. So I cannot use the BeNullOrEmpty() option, because it's not always empty – user14789187 Dec 08 '20 at 19:30
  • this will be true even text1 is null – coder_b Dec 08 '20 at 19:32
  • I've updated the post with better example so maybe it will be easier to get how I need it to work – user14789187 Dec 08 '20 at 19:37
0

You can write your own fluent extensions to define your own assertions:

public static class FluentExtensions
{
    public static AndConstraint<StringAssertions> BeEquivalentLenient(this StringAssertions instance, string expected, string because = "", params object[] becauseArgs)
    {
        Execute.Assertion
            .BecauseOf(because, becauseArgs)
            .ForCondition(beEquivalentLenient(instance.Subject, expected))
            .FailWith("Not equivalent!");

        return new AndConstraint<StringAssertions>(instance);
    }

    private static bool beEquivalentLenient(string s1, string s2)
    {
        if (s1.IsNullOrEmpty())
        {
            return s2.IsNullOrEmpty();
        }

        return s1.Equals(s2);
    }
}

Now you can use it like this:

((string) null).Should().BeEquivalentLenient("");
"".Should().BeEquivalentLenient(null);
"bla".Should().BeEquivalentLenient("b"+"la");
Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
Mo B.
  • 5,307
  • 3
  • 25
  • 42