Advertisement
jdalbey

IOException Test Demo

Jan 30th, 2015
465
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.39 KB | None | 0 0
  1. import java.io.*;
  2. /**
  3.  * Demo of how to test that an IOException is being caught correctly.
  4.  * Low level read operations can throw IOException.
  5.  * If you use scanner, this won't happen.
  6.  */
  7. public class TestIOException extends junit.framework.TestCase
  8. {
  9.     // Return false if write attempt fails
  10.     private boolean write(FileOutputStream out)
  11.     {
  12.         boolean result = true;
  13.         try
  14.         {
  15.             out.write (new byte[3]);
  16.         }
  17.         catch (IOException ex)
  18.         {
  19.             result = false;
  20.         }
  21.         return result;
  22.     }
  23.  
  24.     public void testWrite() throws IOException
  25.     {
  26.         // Fake stream always throws IOException
  27.         MyFakeStream out = new MyFakeStream("XYZ");
  28.         assertFalse(write(out));
  29.     }
  30.    
  31. }
  32.  
  33. import java.io.*;
  34. /** A mock output stream that will ALWAYS throw IOException when writing.
  35.  * @author jdalbey
  36.  * @version 0.1
  37.  */
  38. public class MyFakeStream extends FileOutputStream
  39. {
  40.     public MyFakeStream (String filename) throws IOException
  41.     {
  42.         super (getFDOf (filename));
  43.     }
  44.  
  45.     @Override
  46.     public void write(byte[] b) throws IOException
  47.     {
  48.         throw new IOException();
  49.     }
  50.  
  51.     protected static FileDescriptor getFDOf (String filename) throws IOException
  52.     {
  53.          RandomAccessFile file = new RandomAccessFile (filename, "rw");
  54.          return file.getFD ();
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement