Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test if my object is really serializable?

I am using C# 2.0 with Nunit Test. I have some object that needs to be serialized. These objects are quite complex (inheritance at different levels and contains a lot of objects, events and delegates).

How can I create a Unit Test to be sure that my object is safely serializable?

like image 948
Pokus Avatar asked Oct 25 '08 15:10

Pokus


People also ask

How do you know if an object is serialized?

You can determine whether an object is serializable at run time by retrieving the value of the IsSerializable property of a Type object that represents that object's type.

How do you know if a class is serializable?

If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java. io. Serializable, then it is serializable; otherwise, it's not.

What happens if the object to be serialized?

Q6) What happens if the object to be serialized includes the references to other serializable objects? Ans) If the object to be serialized includes references to the other objects, then all those object's state also will be saved as the part of the serialized state of the object in question.

How do you ignore property serializable?

Try marking the field with [NonSerialized()] attribute. This will tell the serializer to ignore the field.


1 Answers

Here is a generic way:

public static Stream Serialize(object source) {     IFormatter formatter = new BinaryFormatter();     Stream stream = new MemoryStream();     formatter.Serialize(stream, source);     return stream; }  public static T Deserialize<T>(Stream stream) {     IFormatter formatter = new BinaryFormatter();     stream.Position = 0;     return (T)formatter.Deserialize(stream); }  public static T Clone<T>(object source) {     return Deserialize<T>(Serialize(source)); } 
like image 50
GeverGever Avatar answered Sep 30 '22 01:09

GeverGever