×
Overview Versions
- Netbeans 8.2
- JUNIT 4
- JUNIT uses Java Reflection API to run Object Methods
Java IO sample
package fileio; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; public class FileIO { private static final Logger LOGGER = Logger.getLogger( Thread.currentThread().getStackTrace()[0].getClassName() ); /** FileOutputStream Descriptor */ private FileOutputStream fos = null; /** OS-FileName */ final private String fileName ; public FileOutputStream getFileOutputStream() { return fos; } public String getFileName() { return fileName; } public static void main(String[] args) { String writeContent = "This is my Data which needs" + " to be written into the file"; String fileName = "C:/myfile.txt"; //LOGGER.setLevel(Level.FINEST); //LOGGER.setLevel(Level.SEVERE); LOGGER.setLevel(Level.INFO); // Setting current Logger Level Locale.setDefault(new Locale("en", "EN")); // Change Logger Language to English FileIO fileIO = new FileIO(fileName); fileIO.doIO(fileName, writeContent); } public FileIO(String fileName) { this.fileName = fileName; LOGGER.info("FileIO constructor for fileName: " + fileName); } /** * Opens, writes and closes FileOutputStream fos. ** If open was successfull both fileName and FileOutputStream Object are * stored in the related class attributes fileName, fos for later access * @param fName The fileName at OS Level * @param writeContent The message to be written to our FileOutputStream * @return true If write was successfull else return false */ public boolean doIO(String fName,String writeContent) { try { openStream(fName); // Got an excpetion if open failse int bytesWritten = writeToStream( writeContent); boolean ret = closeStream(); String loggerString = new StringBuilder("Byte written to File ") .append( this.fileName ).append(": " ).append(bytesWritten).toString(); LOGGER.info(loggerString); return true; } catch ( IOException ioe) { // Only log the Exception Message - stacktrace should be printed by low level // Exception handler. Close the stream when there is am Exception ! LOGGER.log( Level.SEVERE, ioe.toString() ); return false; } finally{ closeStream(); } } /** * Opens a FileOutputStream fos. *
* If open was successfull both fileName and FileOutputStream Object are * stored in the related class attributes fileName, fos for later access * @param fileName The fileName at OS Level * @throws IOException If stream can't be opened at OS level * @return true If Stream was opened sucessfully */ public boolean openStream (String fileName) throws IOException { String fName = fileName; FileOutputStream lfos; File file; try { if ( fName == null ) { throw new IOException("fileName can't be null"); } //Specify the file path here file = new File(fileName); lfos = new FileOutputStream(file); /* This logic will check whether the file exists or not. If the file * is not found at the specified location it would createa new file */ if (!file.exists()) { file.createNewFile(); } this.fos = lfos; // save the FileOutputStream Descriptor for later usage return true; } catch ( IOException ioe) { String errorMesg = "Error open File-Stream " + fileName; LOGGER.log( Level.SEVERE, ioe.toString(), ioe ); this.fos = null; throw new IOException(errorMesg); } } /** * Writes a String Message to already opened FileOutputStream fos. *
* Note: This methode will convert a potenial NullPointerExceptions tiggered * by either message=null or FileOutputStream fos=null to an IOExeption. * @param message The String to be written to the Stream Descriptor fos * @throws IOException If stream is not already opened at OS level or If messsage is null * @return byteCnt The number of bytes written to our opened Stream */ public int writeToStream( String message) throws IOException { try { /*String content cannot be directly written into * a file. It needs to be converted into bytes */ if (message == null ) { throw new IOException("Message should NOT be null ! "); } // don't need to check for null ! if (!(fos instanceof FileOutputStream)) { throw new IOException("FileOutputStream fos should NOT be null ! "); } byte[] bytesArray = message.getBytes(); int byteCnt = bytesArray.length; fos.write(bytesArray); fos.flush(); String loggerString = new StringBuilder("Successfully written " ) .append( byteCnt ).append(" Bytes to File: ").append(fileName).toString(); LOGGER.info(loggerString); return byteCnt; } catch (IOException ioe) { String errorMesg = "Error writing to File: " + fileName + "\n " + ioe.toString(); LOGGER.log( Level.SEVERE, ioe.toString(), ioe ); throw new IOException(errorMesg); } } /** * Closes FileOutputStream fos. *
* Note: Closing an alreday closed FileOutputStream will not throw any error * Even we get an error during close operation closeStream() methode will only log an error * without re-throwing the underlying Exception. * @return true if Stream was closed successfully */ public boolean closeStream() { try { if (fos != null) { fos.close(); } fos = null; return true; } catch (IOException ioe) { String errorMesg = "Error closing Stream " + fileName; LOGGER.log( Level.SEVERE, ioe.toString(), ioe ); return false; } } }
JUnit test for above IO sample
- Create JUNIT test with Netbeans 8.2: Right Click on Java File -> Tools -> Create/Update Tests
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
String fName = "c:/myFileTest";
instance = new FileIO(fName);
}
@After
public void tearDown() {
}
/**
* Test of main method, of class FileIO.
*/
@Test
public void testMain() {
System.out.println("-> Start Test main()");
String[] args = null;
FileIO.main(args);
System.out.println(" Test main() OK");
}
/**
* Test of openStream method, of class FileIO.
*/
@Test
public void testOpenStream() {
System.out.println("-> Start Test openStream()");
String fName = "c:/myFileTest";
boolean result = false;
// FileIO instance = new FileIO();
boolean expResult = true;
try {
result = instance.openStream(fName);
} catch ( IOException iex) {}
assertTrue("Expected Test Result " + expResult + " - Got: " + result, expResult==result);
System.out.println(" Test openStream() OK!");
}
/*
* Open a Non-Existing File - Should fail with an IOException
*/
@Test (expected=IOException.class)
public void testOpenStreamFailed() throws IOException{
System.out.println("-> Start Test testOpenStreamFailed() - Fails with an IOException !");
String fName = "X:/myFileTestFailed";
boolean result = false;
FileOutputStream expResult = null;
result = instance.openStream(fName);
}
/**
* Test of writeToStream method, of class FileIO.
*/
@Test
public void testWriteToStream() {
String fName = "c:/myFileTest";
FileOutputStream fos;
int bytesWritten = 0;
System.out.println("-> Start Test writeToStream()");
String message = "This is just a Test";
int bytesToBeWritten = message.getBytes().length ;
try {
instance.openStream(fName);
bytesWritten = instance.writeToStream(message);
} catch ( IOException iex) {}
assertTrue("Error:: Expected bytesToBeWritten: " + bytesToBeWritten
+ " - GOT bytesWritten " + bytesWritten ,bytesWritten == bytesToBeWritten );
System.out.println(" Test writeToStream() OK! - bytesWritten: " + bytesWritten);
}
/*
In this test we simulate a write to a Not initialized Stream Desriptor
This Test should fail with an IOExecption
*/
@Test (expected=IOException.class)
public void testWriteToStreamFailed() throws IOException {
String fName = "c:/myFileTest";
FileOutputStream fos = null;
System.out.println("-> Start testWriteToStreamFailed() - Fails with IOException !");
String message = "This is just a Test";
int bytesToBeWritten = message.getBytes().length ;
// instance.writeToStream should trigger an IOException
int bytesWritten = instance.writeToStream( message);
}
/**
* Test of closeStream method, of class FileIO.
* We also test that closing a closed Stream doesn't throw any Exception lile in socket opes
*/
@Test
public void testCloseStream() {
String fName = "c:/myFileTest";
FileOutputStream fos = null;
System.out.println("-> Start Test closeStream()");
String message = "This is just a Test";
boolean result = false;
// FileIO instance = new FileIO();
try {
instance.openStream(fName);
result = instance.closeStream();
} catch ( IOException iex) {}
assertTrue("Error: Expected true in first close !", result);
// Now closing an alreay closed Stream
result = instance.closeStream();
assertTrue("Error: Expected true in 2.nd close !", result);
System.out.println(" Test closeStream() - 2.nd Close OK No Exception !" +
" - ret Status: " + result );
}
/**
* Test of doIO method, of class FileIO.
* Should Work and return true !
*/
@Test
public void testDoIO() {
System.out.println("-> Start Test doIO()");
String fName = "c:/myFileTest";
String writeContent = "This is my Data which needs" +
" to be written into the file";
//FileIO instance = new FileIO();
boolean result = instance.doIO(fName,writeContent);
assertTrue("Error: Expected true !", result);
System.out.println(" Test doIO() OK - result " + result );
}
/**
* Test of doIO method, of class FileIO.
* This test is the most important ONE as we will test that a failed Write closes fos
* descriptor to avoid a resource leak. To test this does we issue an add. write after calling
* doIO(). This add write should fail indicating that fos descriptor was already closed
* TestString : null
* -> doIO() should return false but close fos
* -> An addition Write Test using the closed fos shoud fail too
*/
@Test
public void testDoIOFailed() throws IOException {
System.out.println("-> Start Test testDoIOFailed() - Fails with an Assert !");
String fName = "c:/myFileTest";
String writeContent = null;
//FileIO instance = new FileIO();
boolean result = instance.doIO(fName,writeContent);
assertFalse("Error: Expected false !", result);
// As we can get the Stream closed status form FileOutputStream object we start a test
// write. Note:
// After a failure the Stream should be closed - we expect the the next write to fail !
writeContent = "This WRITE should NOT Work";
int bytesToBeWritten = writeContent.getBytes().length;
int bytesWritten = -1;
try {
bytesWritten = instance.writeToStream( writeContent);
} catch ( IOException e) {}
assertFalse("This Write should fail - as the FOS descpriptor should be closed before!", bytesToBeWritten == bytesWritten );
}
/*
Writing a null Message should reurn an IOException and Not a java.lang.NullPointerException
*/
@Test
public void testWriteFailed() throws IOException{
String fName = "c:/myFileTest";
FileOutputStream fd;
String message = null;
int bytesToBeWritten = -1;
int bytesWritten = -1;
System.out.println("-> Start Test testWriteFailed() - Catches IOException !");
instance.openStream(fName);
fd = instance.getFileOutputStream();
assertTrue(fd instanceof FileOutputStream);
try {
bytesWritten = instance.writeToStream( message);
} catch ( IOException iex) {}
// This Test raises an java.io.IOException: Message should NOT be null at all -
// > bytesWritten remain unchanged
assertTrue("Error:: Expected bytesToBeWritten: " + bytesToBeWritten
+ " - GOT bytesWritten " + bytesWritten ,bytesWritten == bytesToBeWritten );
boolean closeResult = instance.closeStream();
assertTrue("Error: Expected true !", closeResult);
System.out.println(" Test testWriteFailed() OK " );
}
}
JUNIT Test Output
-> Start Test writeToStream() Test writeToStream() OK! - bytesWritten: 19 -> Start testWriteToStreamFailed() - Fails with IOException ! -> Start Test doIO() Test doIO() OK - result true -> Start Test main() Test main() OK -> Start Test closeStream() Test closeStream() - 2.nd Close OK No Exception ! - ret Status: true -> Start Test openStream() Test openStream() OK! -> Start Test testDoIOFailed() - Fails with an Assert ! -> Start Test testWriteFailed() - Catches IOException ! Test testWriteFailed() OK -> Start Test testOpenStreamFailed() - Fails with an IOException ! Mär 30, 2018 1:52:42 PM fileio.FileIOINFORMATION: FileIO constructor for fileName: c:/myFileTest Mär 30, 2018 1:52:42 PM fileio.FileIO writeToStream INFORMATION: Successfully written 19 Bytes to File: c:/myFileTest Mär 30, 2018 1:52:42 PM fileio.FileIO INFORMATION: FileIO constructor for fileName: c:/myFileTest Mär 30, 2018 1:52:42 PM fileio.FileIO writeToStream SCHWERWIEGEND: java.io.IOException: FileOutputStream fos should NOT be null ! java.io.IOException: FileOutputStream fos should NOT be null ! at fileio.FileIO.writeToStream(FileIO.java:122) at fileio.FileIOTest.testWriteToStreamFailed(FileIOTest.java:114) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ... Mär 30, 2018 1:52:42 PM fileio.FileIO INFORMATION: FileIO constructor for fileName: c:/myFileTest Mär 30, 2018 1:52:42 PM fileio.FileIO writeToStream INFORMATION: Successfully written 55 Bytes to File: c:/myFileTest Mär 30, 2018 1:52:42 PM fileio.FileIO doIO INFORMATION: Byte written to File c:/myFileTest: 55 Mär 30, 2018 1:52:42 PM fileio.FileIO INFORMATION: FileIO constructor for fileName: c:/myFileTest Mar 30, 2018 1:52:42 PM fileio.FileIO INFO: FileIO constructor for fileName: C:/myfile.txt Mar 30, 2018 1:52:42 PM fileio.FileIO writeToStream INFO: Successfully written 55 Bytes to File: C:/myfile.txt Mar 30, 2018 1:52:42 PM fileio.FileIO doIO INFO: Byte written to File C:/myfile.txt: 55 Mar 30, 2018 1:52:42 PM fileio.FileIO INFO: FileIO constructor for fileName: c:/myFileTest Mar 30, 2018 1:52:42 PM fileio.FileIO INFO: FileIO constructor for fileName: c:/myFileTest Mar 30, 2018 1:52:42 PM fileio.FileIO INFO: FileIO constructor for fileName: c:/myFileTest Mar 30, 2018 1:52:42 PM fileio.FileIO writeToStream SEVERE: java.io.IOException: Message should NOT be null ! java.io.IOException: Message should NOT be null ! at fileio.FileIO.writeToStream(FileIO.java:119) at fileio.FileIO.doIO(FileIO.java:51) at fileio.FileIOTest.testDoIOFailed(FileIOTest.java:173) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ... Mar 30, 2018 1:52:42 PM fileio.FileIO doIO SEVERE: java.io.IOException: Error writing to File: c:/myFileTest java.io.IOException: Message should NOT be null ! Mar 30, 2018 1:52:42 PM fileio.FileIO writeToStream SEVERE: java.io.IOException: FileOutputStream fos should NOT be null ! java.io.IOException: FileOutputStream fos should NOT be null ! at fileio.FileIO.writeToStream(FileIO.java:122) at fileio.FileIOTest.testDoIOFailed(FileIOTest.java:182) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) .. Mar 30, 2018 1:52:42 PM fileio.FileIO INFO: FileIO constructor for fileName: c:/myFileTest Mar 30, 2018 1:52:42 PM fileio.FileIO writeToStream SEVERE: java.io.IOException: Message should NOT be null ! java.io.IOException: Message should NOT be null ! at fileio.FileIO.writeToStream(FileIO.java:119) at fileio.FileIOTest.testWriteFailed(FileIOTest.java:204) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ... Mar 30, 2018 1:52:42 PM fileio.FileIO INFO: FileIO constructor for fileName: c:/myFileTest Mar 30, 2018 1:52:42 PM fileio.FileIO openStream SEVERE: java.io.FileNotFoundException: X:\myFileTestFailed (Das System kann den angegebenen Pfad nicht finden) java.io.FileNotFoundException: X:\myFileTestFailed (Das System kann den angegebenen Pfad nicht finden) at java.io.FileOutputStream.open0(Native Method) at java.io.FileOutputStream.open(FileOutputStream.java:270) at java.io.FileOutputStream. (FileOutputStream.java:213) at java.io.FileOutputStream. (FileOutputStream.java:162) at fileio.FileIO.openStream(FileIO.java:87) at fileio.FileIOTest.testOpenStreamFailed(FileIOTest.java:77) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ...