下面的代码片段显示了我可以实现此目的的两种方法。第一个是使用MsgPack,第二个测试是使用ServiceStack 的 JSONSerializer。第二个更有利,因为 ServiceStack.Text JSONSerializer 在我工作的整个项目中都使用。
为什么使用 Dictionary<Street,HashSet<int>> 时下面的第二个测试会失败?
[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; }
}