使用String测试DataContractSerializer

时间:2013-07-01 08:29:24

标签: .net wcf datacontractserializer

我正在测试通过WCF服务发送复杂的消息对象并获取各种序列化错误。为了简化这些事情,我试图将其简化为仅测试DataContractSerializer,我根据代码here编写了以下测试:

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,但其中每个都有自己的错误或与{ReadObject DataContractSerializer方法不兼容1}}采用各种不同的重载。

请注意,调整MSDN页面中的代码工作正常,但需要序列化到文件,但我想要串行化到字符串,但我认为我缺少一些重要的东西。

我在上面的代码中遗漏了一些明显的东西吗?

1 个答案:

答案 0 :(得分:4)

XmlWriter中的数据不会立即填充到基础StringWriter。所以你应该在写完之后冲洗作家:

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