Java UNIT Test Exception Handling with @Rule

A nice way to get rid of manual Exception handling in JUnit Tests is this:

 @Rule
 public ExpectedException thrownException = ExpectedException.none();


 @Test
 public void testSomething() {


      // given
        thrownException.expect(MyExpectedException.class);
        thrownException.expectMessage("my expected msg");
        thrownException.reportMissingExceptionWithMessage("my custom msg");
 

      /*  possibly doing setup of mocks which throw the Exception... */

      // when / then
      testee.doSomething(); // throws the Exception...
 }

Kommentare

Beliebte Posts