2013-07-01 67 views
1

我正在測試通過WCF服務發送複雜的消息對象並獲取各種序列化錯誤。爲了簡化事情我想剪下來,只是測試DataContractSerializer,對此我已經基於代碼here寫了下面的測試:使用字符串測試DataContractSerializer

Dim message As TLAMessage = MockFactory.GetMessage 
Dim dcs As DataContractSerializer = New DataContractSerializer(GetType(TLAMessage)) 
Dim xml As String = String.Empty 

Using stream As New StringWriter(), writer As XmlWriter = XmlWriter.Create(stream) 
    dcs.WriteObject(writer, message) 
    xml = stream.ToString 
End Using 

Debug.Print(xml) 

Dim newMessage As TLAMessage 
Dim sr As New StringReader(xml) 
Dim reader As XmlReader = XmlReader.Create(sr) 
dcs = New DataContractSerializer(GetType(TLAMessage)) 
newMessage = CType(dcs.ReadObject(reader, True), TLAMessage) 'Error here 
reader.Close() 
sr.Close() 

Assert.IsTrue(newMessage IsNot Nothing) 

然而,這得到一個不同尋常的錯誤本身ReadObject的呼叫:Unexpected end of file while parsing Name has occurred. Line 1, position 6144

它似乎是一個緩衝錯誤,但我看不到如何在字符串上'ReadToEnd'。我試過使用MemoryStreamDim ms As New MemoryStream(Encoding.UTF8.GetBytes(xml))StreamWriter,但其中每一個都帶有自己的錯誤,或者與DataContractSerializerReadObject方法不兼容,該方法會採用各種不同的重載。

請注意,適應從MSDN頁面的代碼工作正常,但需要序列化到一個文件,但我想序列化和從一個字符串,但我認爲我錯過了一些重要的東西。

我在上面的代碼中丟失了一些明顯的東西嗎?

回答

4

您的XmlWriter的數據沒有立即填充到相關的StringWriter。所以你應該在寫完之後沖洗筆者:

dcs.WriteObject(writer, message) 
writer.Flush() 
xml = stream.ToString() 
+0

所以很明顯,我一直在錯誤的地方看。謝謝 –

+0

不客氣。 –