Created
November 19, 2012 16:33
-
-
Save jbrains/4111662 to your computer and use it in GitHub Desktop.
A new twist on an old pattern for checking for exceptions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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; | |
} | |
} |
Thanks again. I just think in terms of regexes, so I naturally jump there first. (I know... now I have two problems.)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Glad I could help. I should probably admit that I wrote that particular matcher when I worked for youDevise, so I'm partial to it. I'm hoping that it'll make it into Hamcrest at some point.
If you want to match on messages but not worry about punctuation, etc. you can always provide a matcher to
withTheMessage
. For example:withTheMessage(containsString("failure"))
.