I have a little JUnit-Test that export an Object to the FileSystem. In the first place my test looked like this
public void exportTest {
//...creating a list with some objects to export...
JAXBService service = new JAXBService();
service.exportList(list, "output.xml");
}
Usually my test contain a assertion like assertEquals(…). So I changed the code to the following
public void exportCustomerListTest() throws Exception {
// delete the old resulting file, so we can test for a new one at the end
File file = new File("output.xml");
file.delete();
//...creating a list with some objects to export...
JAXBService service = new JAXBService();
service.exportCustomers(list, "output.xml");
// Test if a file has been created and if it contains some bytes
FileReader fis = new FileReader("output.xml");
int firstByte = fis.read();
assertTrue(firstByte != -1 );
}
Do I need this, or was the first approach enough? I am asking because, the first one is actually just “testing” that the code runs, but not testing any results. Or can I rely on the “contract” that if the export-method runs without an exception the test passes?
Thanks
Well, you’re testing that your code runs to completion without any exceptions – but you’re not testing anything about the output.
Why not keep a file with the expected output, and compare that with the actual output? Note that this would probably be easier if you had an overload of
expertCustomerswhich took aWriter– then you could pass in aStringWriterand only write to memory. You could test that in several ways, with just a single test of the overload which takes a filename, as that would just create aFileOutputStreamwrapped in anOutputStreamWriterand then call the more thoroughly tested method. You’d really just need to check that the right file existed, probably.