Purpose: To build a stickynote application using TDD (which I recently learned and now actively regretting)
Problem: I expect all the "Note"s to be serialized and deserialized by thier own individual classes. And I wish to use the TDD approach, but I am unable to even test the happy path of the NoteReader class (deserializer) let alone the corner cases.
Here is the Code:
package com.domainname.applicationname;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;
public class NoteReader {
private final FileInputStream fileInputStream;
public NoteReader(FileInputStream fileInputStream) {
this.fileInputStream = fileInputStream;
}
@SuppressWarnings("unchecked")
public List<Note> load() {
ObjectInputStream objectInputStream = null;
List<Note> output = null;
try {
objectInputStream = new ObjectInputStream(fileInputStream);
output = (List<Note>) objectInputStream.readObject();
objectInputStream.close();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return output;
}
}
and here is the unit testing code:
package com.domainname.applicationname;
import org.junit.*;
import org.mockito.Mockito;
import java.io.*;
import java.util.Arrays;
import java.util.List;
public class NoteReaderTest {
private FileInputStream dummyFileInputStream;
private NoteReader noteReaderDummy;
private List<Note> expectedOutput = Arrays.asList(
new Note("some written text"),
new Note("some other written text", NoteColor.lightGreen)
);
private ByteArrayOutputStream byteArrayOutputStream;
private ObjectOutputStream objectOutputStream;
private byte[] bytesToBeDeserialized;
@Before
public void setUp() throws IOException {
dummyFileInputStream = Mockito.mock(FileInputStream.class);
noteReaderDummy = new NoteReader(dummyFileInputStream);
byteArrayOutputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
}
@After
public void tearDown() throws IOException {
noteReaderDummy = null;
byteArrayOutputStream.flush();
objectOutputStream.flush();
objectOutputStream.close();
}
@Test
public void shouldLoadTheListOfNotes() throws IOException {
//given
objectOutputStream.writeObject(expectedOutput);
bytesToBeDeserialized = byteArrayOutputStream.toByteArray();
int intValueOfByteArray = dummyFileInputStream.read(bytesToBeDeserialized);
//when
Mockito.when(
dummyFileInputStream.read()
).thenReturn(
intValueOfByteArray
);
//then
Assert.assertEquals(
"the notes have not been loaded",
expectedOutput,
noteReaderDummy.load()
);
}
}
This has b/me an infinite loop and it's driving me nuts.
Question: How do I test a deserialization class? What am I doing wrong in the above code?