Skip to content

Instantly share code, notes, and snippets.

@jbrains
Created November 19, 2012 16:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbrains/4111662 to your computer and use it in GitHub Desktop.
Save jbrains/4111662 to your computer and use it in GitHub Desktop.
A new twist on an old pattern for checking for exceptions
@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;
}
}
@jbrains
Copy link
Author

jbrains commented Nov 20, 2012

Thank you for the tip on youDevise/matchers. I don't typically like to match on exception messages, because that makes the assertion hyperactive (fail too easily), but I see how not depending on the exception type/instance would provide a different dimension of freedom to change the code. It feels like a style choice to me, but only because I haven't tried it your way extensively yet.

Either way, I do like the running(...).throwsException(...) style. Thanks for that.

@SamirTalwar
Copy link

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")).

@jbrains
Copy link
Author

jbrains commented Nov 20, 2012

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