gpt4 book ai didi

c# - FluentAssertions - 如何使 ShouldBeEquivalentTo 比较空和 null 是否相等

转载 作者:太空狗 更新时间:2023-10-29 23:05:51 28 4
gpt4 key购买 nike

我正在使用 Fluent Assertion 库作为我对一些自定义序列化代码进行单元测试的一部分,我正在寻找一种方法来强制 ShouldBeEquivalentTo 将 null 和空列表比较为相等。

基本上,我的测试看起来像这样:

    [Test]
public void Should_be_xxx()
{
ClassWithList one = new ClassWithList { Id = "ten", Items = null };

string serialized = Serialize(one);
ClassWithList two = Deserialize(serialized);

two.ShouldBeEquivalentTo(one);
}

但是,Deserialize 方法的一个特点是,如果输入数据中缺少集合类型,它会将反序列化类上的属性设置为空列表,而不是 null。所以,非常简单,我最终遇到的情况是实例二,Items = new List<string>而不是 null。

显然,我可以设置 one.Items = new List<string>()在比较之前,但实际上我有大量复杂的域对象,我在这些方法中断言,我正在寻找一个通用的解决方案。换句话说,有谁知道如何使以下测试通过:

    public class ClassWithList
{
public string Id { get; set; }
public List<string> Items { get; set; }
}

[Test]
public void Should_be_xxx()
{
ClassWithList one = new ClassWithList { Id = "ten", Items = null };
ClassWithList two = new ClassWithList { Id = "ten", Items = new List<string>() };

two.ShouldBeEquivalentTo(one);
}

换句话说,我希望将以下测试应用于类 X 中的所有集合,作为比较等价性的一部分:

  if (subject.Items == null)
{
expected.Items.Should().BeEmpty();
}
else
{
expected.Items.Should().BeEquivalentTo(subject.Items);
}

最佳答案

根据上述丹尼斯提供的信息,我能够通过以下实际代码解决此问题:

    public class ClassWithList
{
public string Id { get; set; }
public List<string> Items { get; set; }
public List<ClassWithList> Nested { get; set; }
}

[TestClass]
public class Test
{
[TestMethod]
public void Should_compare_null_to_empty()
{
ClassWithList one = new ClassWithList { Id = "ten", Items = null, Nested = new List<ClassWithList> { new ClassWithList { Id = "a" } } };
ClassWithList two = new ClassWithList { Id = "ten", Items = new List<string>(), Nested = new List<ClassWithList> { new ClassWithList { Id = "a", Items = new List<string>(), Nested = new List<ClassWithList> { } } } };

two.ShouldBeEquivalentTo(one, opt => opt
.Using<IEnumerable>(CheckList)
.When(info => typeof(IEnumerable).IsAssignableFrom(info.CompileTimeType)));
}

private void CheckList(IAssertionContext<IEnumerable> a)
{
if (a.Expectation == null)
{
a.Subject.Should().BeEmpty();
}
else
{
a.Subject.ShouldBeEquivalentTo(a.Expectation, opt => opt
.Using<IEnumerable>(CheckList)
.When(info => typeof(IEnumerable).IsAssignableFrom(info.CompileTimeType)));
}
}
}

关于c# - FluentAssertions - 如何使 ShouldBeEquivalentTo 比较空和 null 是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39084977/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com