Fluent Assertions - null and empty string comparison

Viewed 1592

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).

2 Answers

well you can use AssertionScope

 string text1 = "";
        string text2 = null;
        using (new AssertionScope())
        {
            test1.Should().BeOneOf("foo", null, "");
            test2.Should().BeOneOf("foo", null, "");
        };

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");
Related