Introduction
When you have an object that is marked with a <DataContract>
, it is easy to miss out one or more of the members that should be serialised by forgetting to mark them with a <DataMember>
attributes. Therefore, each member should have a unit test to check that it does perform a round trip.
Using the Code
Given a class which is serializable using a data contract - for example:
<DataContract>
Public NotInheritable Class QueryParameter(Of TValue)
<DataMember(Name:="ParameterName")>
ReadOnly m_name As String
<DataMember(Name:="ParameterIndex")>
ReadOnly m_index As Integer
<DataMember(Name:="ParameterValue")>
ReadOnly m_value As TValue
Public ReadOnly Property Name As String
Get
Return m_name
End Get
End Property
Public ReadOnly Property Index As Integer
Get
Return m_index
End Get
End Property
Public ReadOnly Property Value As TValue
Get
Return m_value
End Get
End Property
Private Sub New(ByVal nameInit As String, ByVal indexInit As Integer, ByVal valInit As TValue)
m_name = nameInit
m_index = indexInit
m_value = valInit
End Sub
Public Shared Function Create(Of TValueType)(ByVal name As String, ByVal index As Integer, ByVal value As TValueType) As QueryParameter(Of TValueType)
Return New QueryParameter(Of TValueType)(name, index, value)
End Function
End Class
You can create a unit test to test that the value services a round-trip thus:
<TestMethod>
Public Sub Value_String_Serialisation_RoundTrip()
Dim expected As String = "This is a test"
Dim actual As String = "Actual value"
Dim paramObj As QueryParameter(Of String) =
QueryParameter(Of String).Create("test", 0, expected)
Dim ser As New System.Runtime.Serialization.DataContractSerializer(paramObj.GetType())
Dim ms As New System.IO.MemoryStream(5000)
ser.WriteObject(ms, paramObj)
ms.Seek(0, IO.SeekOrigin.Begin)
Dim paramObjDeserialised As QueryParameter(Of String)
paramObjDeserialised = ser.ReadObject(ms)
actual = paramObjDeserialised.Value
Assert.AreEqual(expected, actual)
End Sub
Points of interest
- You should always make sure that the actual and expected values are initialised to different values at the start of the unit test and that neither is set to the default for the data type.
- You should have one unit test for each serialisable property the class contains