Is there any point Unit testing serialization?

后端 未结 13 927
慢半拍i
慢半拍i 2021-02-01 23:38

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

13条回答
  •  清歌不尽
    2021-02-02 00:20

    I would argue that it is essential to unit test serialization if it is vitally important that you can read data between versions. And you must test with "known good" data (i.e. it isn't sufficient to simply write data in the current version and then read it again).

    You mention that you don't have a schema... why not generate one? Either by hand (it isn't very hard), or with xsd.exe. Then you have something to use as a template, and you can verify this just using XmlReader. I'm doing a lot of work with xml serialization at the moment, and it is a lot easier to update the schema than it is to worry about whether I'm getting the data right.

    Even XmlSerializer can get complex; particularly if you involve subclasses ([XmlInclude]), custom serialization (IXmlSerializable), or non-default XmlSerializer construction (passing additional metadata at runtime to the ctor). Another possibility is creative use of [XmlIngore], [XmlAnyAttribute] or [XmlAnyElement]; for example you might support unexpected data for round-trip (only) in version X, but store it in a known property in version Y.


    With serialization in general:

    The reason is simple: you can break the data! How badly you do this depends on the serializer; for example, with BinaryFormatter (and I know the question is XmlSerializer), simply changing from:

    public string Name {get;set;}
    

    to

    private string name;
    public string Name {
        get {return name;}
        set {name = value; OnPropertyChanged("Name"); }
    }
    

    could be enough to break serialization, as the field name has changed (and BinaryFormatter loves fields).

    There are other occasions when you might accidentally rename the data (even in contract-based serializers such as XmlSerializer / DataContractSerializer). In such cases you can usually override the wire identifiers (for example [XmlAttribute("name")] etc), but it is important to check this!

    Ultimately, it comes down to: is it important that you can read old data? It usually is; so don't just ship it... prove that you can.

提交回复
热议问题