title: JUnit: Testing for an exception of certain type
body: <p>I am wanting to know if I can test (using JUnit) that a specific message generated by an exception gets thrown rather than just "whether or not" an exception was thrown.
  For example the JunitTest.java code will actually pass the test because an exception was thrown but if I also wanted to test that the string generated by the exception was equal to: <em>"Test Exception: Integer may not be negative.."</em> is this possible?</p>
  
  <p><strong>TestException.java</strong></p>
  
  <pre><code>public class TestException extends Exception {  
      /**
       * @param message informative message about the problem found
       */
      public TestException (String message) {
          super("Test Exception: " + message);
      }
  }
  </code></pre>
  
  <p><strong>Test.java</strong></p>
  
  <pre><code>public void function(Integer mustBePositive) throws TestException {
      if (mustBePositive &lt; 0) {
          throw new TestException("Integer may not be negative..");
      }
      else {
          mustBePositive = myNum
      }
  }
  </code></pre>
  
  <p><strong>JunitTest.java</strong></p>
  
  <pre><code>import org.junit.*;
  
  public class JUnitTest {
  
      @Test(expected = TestException.class)
      public void functionTest() throws TestException {
          function(-1);
      }
  }
  </code></pre>