package example.protostuff; import example.protostuff.SerializationUtil; import io.protostuff.LinkedBuffer; import io.protostuff.ProtostuffIOUtil; import io.protostuff.Schema; import io.protostuff.runtime.RuntimeSchema; import org.junit.Assert; import org.junit.Test; import java.util.*; import static org.junit.Assert.*; /** * Created by jackeylv on 2016/7/14. */ public class SerializationUtilTest { private void testHelper(Object obj){ byte[] bytes = SerializationUtil.marshall(obj); System.out.printf("object = %s, object.class = %s, bytes.length = %d, bytes = %s%n", obj, null != obj ? obj.getClass() : null, bytes.length, bytes); Object desr = SerializationUtil.unmarshall(bytes); if (null == obj && null == desr){ return; } if (null == obj && null != desr){ Assert.fail("desc != null"); } if (obj.getClass().isArray()){ System.out.println(Arrays.deepToString((Object[]) obj)); System.out.println(Arrays.deepToString((Object[]) desr)); Assert.assertArrayEquals(((Object[]) obj), ((Object[]) desr)); } else { Assert.assertEquals(obj, desr); } } @Test public void testListWithNullElement() throws Exception { LinkedList lst = new LinkedList(); testHelper(lst); lst.add(1); lst.add("hello"); lst.add("2.456"); testHelper(lst); lst.add(null); lst.add("hi"); testHelper(lst); } @Test public void testSetWithNullElement() throws Exception { HashSet set = null; testHelper(set); set = new HashSet(); testHelper(set); set.add(1); set.add("23"); set.add(null); testHelper(set); } @Test public void testObjectArrayWithNullElements() throws Exception { Object[] objects = new Object[]{ 1, null, "hello", null, 345 }; testHelper(objects); } /** * FIXME We can fix it with {@link ClassWrapper}. Or any other suggestions? * java.lang.RuntimeException: The root object can neither be an abstract class nor interface: "[Ljava.lang.Integer; * @throws Exception */ @Test public void testIntArrayWithRawPS() throws Exception { Integer[] arr = new Integer[]{0,1,2,3}; Schema schema = RuntimeSchema.getSchema(arr.getClass()); LinkedBuffer buffer = LinkedBuffer.allocate(); try { byte[] bytes = ProtostuffIOUtil.toByteArray(arr,schema,buffer); Integer[] ret = (Integer[]) schema.newMessage(); ProtostuffIOUtil.mergeFrom(bytes, ret, schema); Assert.assertArrayEquals(arr, ret); } finally { buffer.clear(); } } }