Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 流畅的断言-空字符串和空字符串比较_C#_Fluent Assertions - Fatal编程技术网

C# 流畅的断言-空字符串和空字符串比较

C# 流畅的断言-空字符串和空字符串比较,c#,fluent-assertions,C#,Fluent Assertions,是否可以强制流畅的断言传递Should().Be(),以比较空字符串和空字符串?或者这可以用Beequivalento来实现 例如: text1.Should().Be(text2); 我希望上述代码在以下情况下通过: text1将是‘foo’,text2将是‘foo’(只是标准行为) text1为空字符串,text2为空 所以我需要做一个可以比较字符串的断言,但是如果其中一个是空的,而另一个是空的,它仍然应该通过 一些背景: 我需要它来做硒自动测试。我有一些Dto,我将其发送到api以创

是否可以强制流畅的断言传递Should().Be(),以比较空字符串和空字符串?或者这可以用Beequivalento来实现

例如:

text1.Should().Be(text2);
我希望上述代码在以下情况下通过:

  • text1将是‘foo’,text2将是‘foo’(只是标准行为)
  • text1为空字符串,text2为空
所以我需要做一个可以比较字符串的断言,但是如果其中一个是空的,而另一个是空的,它仍然应该通过

一些背景:


我需要它来做硒自动测试。我有一些Dto,我将其发送到api以创建一个产品表作为测试前提条件(Dto的一些字段可以为空)。然后,在应用程序的UI中,此null显示为空字符串。稍后在测试中,我将检查每一列是否显示正确的数据,我希望能够使流畅的断言在空字符串和null之间传递断言(当然,如果比较了两个正确的字符串->当Dto字段都不为null时,仍然传递断言)。

您可以使用断言范围

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

您可以编写自己的fluent扩展来定义自己的断言:

    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);
        }
    }

正如我所说的,Dto的这个字段可以为null,但在大多数情况下,我都会使用字符串来表示它们。若我将填充Dto的所有字段,那个么在UI中我将看到正确的字符串。所以我不能使用BeNullOrEmpty()选项,因为它并不总是空的。即使text1为空,这也将是真的。我已经用更好的例子更新了帖子,所以可能更容易得到我需要它的工作方式。这回答了你的问题吗?
            ((string) null).Should().BeEquivalentLenient("");
            "".Should().BeEquivalentLenient(null);
            "bla".Should().BeEquivalentLenient("b"+"la");