views:

973

answers:

4

I am looking for example code that provides a unit test to serialize and deserialize an object from a memory stream. I have found examples using C# 2.0, however my current project uses VB.NET 1.1 (don't ask me why...), so the solution can not use generics. I am also using the NUnit framework for the unit tests.

Thanks!

A: 

Hmm...so you are trying to write a unit test for serialization? Or for streams? This is hopefully done by MS already...but if you don't trust or implement something on your own...you could just fill object with some data, save it, restore it, and check if the fields values are in place?

badbadboy
Here is essentially what I'm trying to do, but in VB.NET 1.1:http://stackoverflow.com/questions/236599/how-to-unit-test-if-my-object-is-really-serializablable
Technobabble
+1  A: 

If all you want to do is to ensure that they are serializable then all you should have to do it to do a serialization of an object and make sure no XmlSerializationException was thrown

[Test]
public void ClassIsXmlSerializable()
{
   bool exceptionWasThrown = false;

   try
   {
      // .. serialize object
   }
   catch(XmlSerializationException ex)
   {
      exceptionWasThrown = true;
   }

   Asset.IsFalse(exceptionWasThrown, "An XmlSerializationException was thrown. The type xx is not xml serializable!");
}
TheCodeJunkie
Sorry didnt see you were using VB.NET.. let me know if you want me to translate it to VB.NET for you
TheCodeJunkie
No need, I can read C# comfortably. However, I've run into some instances where VB.NET and C# differ consierably on certain features (like when using the [field:NonSerialized] attribute declaration, which doesn't seem to be supported in VB.NET).
Technobabble
If this was a solution to your problem then please make it as the answer
TheCodeJunkie
A: 

This is the pattern I've settled upon:

<Test()> _
Public Sub SerializationTest()
    Dim obj As New MySerializableObject()
    'Perform additional construction as necessary

    Dim obj2 As MySerializableObject
    Dim formatter As New BinaryFormatter
    Dim memoryStream As New MemoryStream()

    'Run through serialization process
    formatter.Serialize(memoryStream, obj)
    memoryStream.Seek(0, SeekOrigin.Begin)
    obj2 = DirectCast(formatter.Deserialize(memoryStream), MySerializableObject)

    'Test for equality using Assert methods
    Assert.AreEqual(obj.Property1, obj.Property1)
    'etc...
End Sub
Technobabble
MatrixFrog
+1  A: 

NUnit has built in support for this which makes it quite a bit easier:

Dim obj As New MySerializableObject()
Assert.That(obj, Is.BinarySerializable)

Or for xml:

Dim obj As New MySerializableObject()
Assert.That(obj, Is.XmlSerializable)
Patrik Hägne
I had never known about this until now, just been using it, far better :)
MJJames