Wednesday, 2 October 2013

junit: another pattern to test exception

junit: another pattern to test exception

I work on a project with many "BusinessException" that embedded errorCode.
In every unit test for exception, I have to test these error code
repeating this kind of pattern :
@Test
public void
zipFileReaderCtorShouldThrowAnExceptionWithInexistingArchive() {
try {
zfr = new ZipFileReader("unexpected/path/to/file");
fail("'BusinessZipException' not throwed");
} catch (BusinessZipException e) {
assertThat("Unexpected error code", e.getErrorCode(),
is(ErrorCode.FILE_NOT_FOUND));
} catch (Exception e) {
fail("Unexpected Exception: '" + e + "', expected:
'BusinessZipException'");
}
}
(use of junit annotation is impossible due to error code testing)
I was boring to do this, particularly because I had to copy/paste
exception name in fail()'s error message.
So, I wrote a Util class. I use an abstract class to handle exception
assert testing.
public abstract class TestExceptionUtil {
public void runAndExpectException(Class expectedException, String
expectedErrorCode) {
String failUnexpectedExceptionMessage = "Unexpected exception.
Expected is: '%s', but got: '%s'";
try {
codeToExecute();
fail("'" + expectedException.getName() + "' not throwed");
} catch (BusinessException e) {
if (e.getClass().equals(expectedException)) {
assertThat("Exception error code not expected",
e.getErrorCode(), is(expectedErrorCode));
} else {
fail(String.format(failUnexpectedExceptionMessage,
expectedException.getName(), e));
}
} catch (Exception e) {
fail(String.format(failUnexpectedExceptionMessage,
expectedException.getName(), e));
}
}
abstract public void codeToExecute();
}
Then, client use it in this way :
@Test
public void
zipFileReaderCtorShouldThrowAnExceptionWithInexistingArchive() {
new TestExceptionUtil() {
@Override
public void codeToExecute() {
zfr = new ZipFileReader("unexpected/path/to/file");
}
}.runAndExpectException(BusinessTechnicalException.class,
ErrorCode.FILE_NOT_FOUND);
}
Do you think it's "clean" ? Do you think it can be ameliorated ? Do you
think it's too heavy and/or useless ? My primary objective is to
uniformize testing exception in our dev team. (and of course factorize
code)
Thanks for reading !

No comments:

Post a Comment