いくつかのカスタムシリアル化コードの単体テストの一部としてFluentAssertionライブラリを使用しており、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メソッドの機能の1つは、コレクションタイプが入力データにない場合、逆シリアル化されたクラスのプロパティをnullではなく空のリストに設定することです。したがって、非常に単純化すると、インスタンスItems = new List<string>
がnullではなく2になる状況になります。
明らかに、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)));
}
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加