Update SerializationUnitTest.java

Changes to add more tests.
This commit is contained in:
Amitabh Tiwari 2021-10-24 07:03:35 +05:30
parent 2fa7ea1f22
commit 40c6b489d8
1 changed files with 21 additions and 0 deletions

View File

@ -3,9 +3,11 @@ package com.baeldung.serialization;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
@ -23,6 +25,25 @@ public class SerializationUnitTest {
objectOutputStream.writeObject(address);
}
}
@Test
public void whenSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
Person p = new Person();
p.setAge(20);
p.setName("Joe");
FileOutputStream fileOutputStream = new FileOutputStream("yofile.txt");
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) {
objectOutputStream.writeObject(p);
}
FileInputStream fileInputStream = new FileInputStream("yofile.txt");
try ( ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) {
Person p2 = (Person) objectInputStream.readObject();
assertTrue(p2.getAge() == p.getAge());
assertTrue(p2.getName().equals(p.getName()));
}
}
@Test(expected = ClassCastException.class)
public void whenSerializingUsingApacheCommons_ThenThrowsError() {