Comments

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.

(TestingIoFailure.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@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.)