Is there any point Unit testing serialization?

2019-03-09 22:42发布

I have a class that serializes a set of objects (using XML serialization) that I want to unit test.

My problem is it feels like I will be testing the .NET implementation of XML serialization, instead of anything useful. I also have a slight chicken and egg scenario where in order to test the Reader, I will need a file produced by the Writer to do so.

I think the questions (there's 3 but they all relate) I'm ultimately looking for feedback on are:

  1. Is it possible to test the Writer, without using the Reader?
  2. What is the best strategy for testing the reader (XML file? Mocking with record/playback)? Is it the case that all you will really be doing is testing property values of the objects that have been deserialized?
  3. What is the best strategy for testing the writer!

Background info on Xml serialization

I'm not using a schema, so all XML elements and attributes match the objects' properties. As there is no schema, tags/attributes which do not match those found in properties of each object, are simply ignored by the XmlSerializer (so the property's value is null or default). Here is an example

<MyObject Height="300">
    <Name>Bob</Name>
    <Age>20</Age>
<MyObject>

would map to

public class MyObject
{
  public string Name { get;set; }
  public int Age { get;set; }

  [XmlAttribute]
  public int Height { get;set; }
}

and visa versa. If the object changed to the below the XML would still deserialize succesfully, but FirstName would be blank.

public class MyObject
{
  public string FirstName { get;set; }
  public int Age { get;set; }

  [XmlAttribute]
  public int Height { get;set; }
}

An invalid XML file would deserialize correctly, therefore the unit test would pass unless you ran assertions on the values of the MyObject.

13条回答
Animai°情兽
2楼-- · 2019-03-09 23:31

Do you need to be able to do backward compatibility? If so, it may be worth building up unit tests of files produced by old versions which should still be able to be deserialized by new versions.

Other than that, if you ever introduce anything "interesting" it may be worth a unit test to just check you can serialize and deserialize just to make sure you're not doing something funky with a readonly property etc.

查看更多
登录 后发表回答