|
| 1 | +package com.baeldung.externalizable; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import java.io.*; |
| 6 | + |
| 7 | +import static org.junit.Assert.assertTrue; |
| 8 | + |
| 9 | +public class ExternalizableUnitTest { |
| 10 | + |
| 11 | + private final static String OUTPUT_FILE = "externalizable.txt"; |
| 12 | + |
| 13 | + @Test |
| 14 | + public void whenSerializing_thenUseExternalizable() throws IOException, ClassNotFoundException { |
| 15 | + |
| 16 | + Country c = new Country(); |
| 17 | + c.setCapital("Yerevan"); |
| 18 | + c.setCode(374); |
| 19 | + c.setName("Armenia"); |
| 20 | + |
| 21 | + FileOutputStream fileOutputStream = new FileOutputStream(OUTPUT_FILE); |
| 22 | + ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); |
| 23 | + c.writeExternal(objectOutputStream); |
| 24 | + |
| 25 | + objectOutputStream.flush(); |
| 26 | + objectOutputStream.close(); |
| 27 | + fileOutputStream.close(); |
| 28 | + |
| 29 | + FileInputStream fileInputStream = new FileInputStream(OUTPUT_FILE); |
| 30 | + ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); |
| 31 | + |
| 32 | + Country c2 = new Country(); |
| 33 | + c2.readExternal(objectInputStream); |
| 34 | + |
| 35 | + objectInputStream.close(); |
| 36 | + fileInputStream.close(); |
| 37 | + |
| 38 | + assertTrue(c2.getCode() == c.getCode()); |
| 39 | + assertTrue(c2.getName().equals(c.getName())); |
| 40 | + } |
| 41 | + |
| 42 | + @Test |
| 43 | + public void whenInheritanceSerialization_then_UseExternalizable() throws IOException, ClassNotFoundException { |
| 44 | + |
| 45 | + Region r = new Region(); |
| 46 | + r.setCapital("Yerevan"); |
| 47 | + r.setCode(374); |
| 48 | + r.setName("Armenia"); |
| 49 | + r.setClimate("Mediterranean"); |
| 50 | + r.setPopulation(120.000); |
| 51 | + |
| 52 | + FileOutputStream fileOutputStream = new FileOutputStream(OUTPUT_FILE); |
| 53 | + ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); |
| 54 | + r.writeExternal(objectOutputStream); |
| 55 | + |
| 56 | + objectOutputStream.flush(); |
| 57 | + objectOutputStream.close(); |
| 58 | + fileOutputStream.close(); |
| 59 | + |
| 60 | + FileInputStream fileInputStream = new FileInputStream(OUTPUT_FILE); |
| 61 | + ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); |
| 62 | + |
| 63 | + Region r2 = new Region(); |
| 64 | + r2.readExternal(objectInputStream); |
| 65 | + |
| 66 | + objectInputStream.close(); |
| 67 | + fileInputStream.close(); |
| 68 | + |
| 69 | + assertTrue(r2.getPopulation() == null); |
| 70 | + } |
| 71 | +} |
0 commit comments