以下のコード スニペットは、これを実現するための 2 つの方法を示しています。1 つ目はMsgPackを使用しており、2 つ目のテストはServiceStack の JSONSerializerを使用しています。私が取り組んでいるプロジェクト全体で ServiceStack.Text JSONSerializer が使用されているため、2 番目の方法がより有利です。
Dictionary<Street,HashSet<int>> を使用すると、以下の 2 番目のテストが失敗するのはなぜですか?
[TestFixture]
public class NeighbourhoodTests
{
private Neighbourhood _myNeighbourhood;
private Street _street;
[SetUp]
public void SetupOnEachTest()
{
_street = new Street() { Name = "Storgate" };
_myNeighbourhood = SetupMyNeighbourhood(_street);
}
private static Neighbourhood SetupMyNeighbourhood(Street street)
{
var myNeighbourhood = new Neighbourhood();
myNeighbourhood.Addresses = new Dictionary<Street, HashSet<int>>();
myNeighbourhood.Addresses.Add(street, new HashSet<int>(new[] { 1, 2, 3, 4 }));
myNeighbourhood.LocalCouncilName = "Stavanger";
myNeighbourhood.RegionName = "Rogaland";
return myNeighbourhood;
}
[Test]
public void TestNeighbourhoodClass_OnMsgPackDeserialization_AddressesShouldEqualOriginalInput()
{
ObjectPacker packer = new ObjectPacker();
var packedMessageBytes = packer.Pack(_myNeighbourhood);
var unpackedMessage = packer.Unpack(packedMessageBytes);
Assert.That(unpackedMessage.RegionName, Is.EqualTo("Rogaland"));
Assert.That(unpackedMessage.Addresses, Is.Not.Empty);
Assert.That(unpackedMessage.Addresses.Keys.Any(key => key.Name.Equals(_street.Name)));
}
[Test]
public void TestNeighbourhoodClass_OnServiceStackJsonTextDeserialization_AddressesShouldEqualOriginalInput()
{
string serialisedMessage = JsonSerializer.SerializeToString(_myNeighbourhood);
var deserializedMessage = JsonSerializer.DeserializeFromString(serialisedMessage);
Assert.That(deserializedMessage.RegionName, Is.EqualTo("Rogaland"));
Assert.That(deserializedMessage.Addresses, Is.Not.Empty);
Assert.That(deserializedMessage.Addresses.Keys.Any(key => key.Name.Equals(_street.Name)));
}
}
public class Neighbourhood
{
public Dictionary<Street, HashSet<int>> Addresses { get; set; }
public string LocalCouncilName { get; set; }
public string RegionName { get; set; }
}