A new twist on an old pattern
I’m coding like it’s 2000, meaning in Java. I thought I’d never see anything new regarding writing a test that expects to catch a specific exception. I saw something new, and I wonder who else has independently discovered it.
@Test public void ioFailure() throws Exception { final IOException ioFailure = new IOException("Simulating a failure writing to the file."); try { new WriteTextToFileActionImpl() { @Override protected FileWriter fileWriterOn(File path) throws IOException { return new FileWriter(path) { @Override public void write(String str, int off, int len) throws IOException { throw ioFailure; } }; } }.writeTextToFile("::text::", new File("anyWritableFile.txt")); fail("How did you survive the I/O failure?!"); } catch (IOException success) { if (success != ioFailure) throw success; } }
Please add your comments at gist.github.com.
(If you can’t see the code snippet inline, then click here.)