我正在使用Fluent断言库作为我的一些自定义序列化代码的单元测试的一部分,我正在寻找一种方法来强制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);
}
根据Dennis上面的信息,我能够通过以下实际代码解决这个问题:
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)));
}
}
}
您必须实现自定义'IEquivalencyStep'或使用'选项。使用(自定义的动作).WhenTypeIs(谓词)。
创建IAssertionRule
:
public class EnumerableNullEmptyEquivalenceRule : IAssertionRule
{
public bool AssertEquality(IEquivalencyValidationContext context)
{
// not applicable - return false
if (!typeof(IEnumerable).IsAssignableFrom(context.SelectedMemberInfo.MemberType)) return false;
return context.Expectation == null && ((IEnumerable)context.Subject).IsNullOrEmpty();
}
}
然后应用到你的BeEquivalentTo
调用:
actual.Should().BeEquivalentTo(expected, opt => opt.Using(new EnumerableNullEmptyEquivalenceRule()));