JUnit 4 - How to write a Test for an expected Exception
Not only the good weather tests should be done, also the bad weather tests. So its often the case, that you want the method you test to provoke to throw an exception. In this case of course the test was successful. So how to do this in a human readable way?
package com.tumblr.javaknowledgecafe.junit; import junit.framework.Assert; import org.junit.Test; public class JUnitExpectedException { // how to write @Test(expected = Exception.class) public void testThrowException() throws Exception { this.methodThatThrowsAnException(); } // how you wrote it before @Test public void testThrowExceptionOld() { try { this.methodThatThrowsAnException(); Assert.fail(); } catch (Exception e) { // ignore } } private void methodThatThrowsAnException() throws Exception { throw new Exception(); } }
So with the expected you get rid of FIVE lines + the code is much more readable!
Yeah you maybe say, its only four because of the //ignore-line. But I think its a bad habit to not write this line, because an other reader or maybe just you some weeks later, don't know anymore, did you forget to do something there? Much better it is with a longer statement like: //ignore, because a default value is chosen











