December 2002
Intermediate to advanced
288 pages
9h 46m
English
Because marshalling in RMI is always based on streams, it’s very easy to write unit tests for your marshalling code. And doing so can save you a lot of headaches as you modify your codebase. All you need to do is use streams that map to byte arrays in memory. For example, the following code creates a deep copy of an object and then makes sure the deep copy is equal to the original instance:
public static boolean testSerialization(Serializable object) throws Exception {
Object secondObject = makeDeepCopy(object);
boolean hashCodeComparison = (object.hashCode() == secondObject.hashCode( ));
boolean equalsComparison = object.equals(secondObject);
return hashCodeComparison && equalsComparison;
}
private static object makeDeepCopy(Serializable object) throws Exception{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream( );
ObjectOutputStream objectOutputStream = new
ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(object);
objectOutputStream.flush( );
byte[] bytes = byteArrayOutputStream.toByteArray( );
ByteArrayInputStream byteArrayInputStream= new ByteArrayInputStream(bytes);
ObjectInputStream objectInputStream = new
ObjectInputStream(byteArrayInputStream);
SerializationTest deepCopy = (SerializationTest) objectInputStream.readObject( );
return deepCopy;
}If you insert tests for each value object in your codebase, and then run them occasionally (for example, as unit tests in either Cactus or JUnit), you’ll ...