Mik*_*ton 5 c# fluent-assertions
我正在使用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);
}
Run Code Online (Sandbox Code Playgroud)
但是,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);
}
Run Code Online (Sandbox Code Playgroud)
换句话说,我希望将以下测试应用于类X中的所有集合,作为比较等效性的一部分:
if (subject.Items == null)
{
expected.Items.Should().BeEmpty();
}
else
{
expected.Items.Should().BeEquivalentTo(subject.Items);
}
Run Code Online (Sandbox Code Playgroud)
您必须实现自定义的 'IEquivalencyStep' 或 u.se 'options.Using(custom action).WhenTypeIs(predicate)。
根据上面来自丹尼斯的信息,我能够通过以下实际代码解决这个问题:
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)));
}
}
}
Run Code Online (Sandbox Code Playgroud)