下面的代码片段显示了我可以实现此目的的两种方法。第一个是使用MsgPack https://github.com/msgpack/msgpack-cli第二个测试是使用ServiceStack 的 JSONSerializer https://github.com/ServiceStack/ServiceStack.Text。第二个更有利,因为 ServiceStack.Text JSONSerializer 在我正在从事的整个项目中使用。
为什么使用 Dictionary> 时下面的第二个测试失败?
[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; }
}
啊啊,感谢 @mortenrøgenes- 事实证明,我必须将 Neighborhood 类的 Addresses 属性包装到它自己的类型中,如下所示:
public class Addresses
{
public Street Street{ get; set; }
public HashSet<int> HouseNumbers { get; set; }
}
public class Neighbourhood
{
public Addresses { get; set; }
public string LocalCouncilName { get; set; }
public string RegionName { get; set; }
}
这样 ServiceStack JSONSerializer 就能工作并且测试也会通过。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)