JUnit4 @Test (expected = MyException.class) VS try / catch

I reflect on best practices for handling exceptions and unit tests because we are trying to use some of the best code methods.

In a previous article regarding best practices found in our wiki, “Don't use try / catch, but use Junit4 @Test (expect = MyException.class)”, without further information. I'm not sure.

Many of our custom exceptions have an Enum to identify the cause of the failure. As a result, I would rather see a test like:

@Test
public void testDoSomethingFailsBecauseZzz() {
try{
   doSomething();
} catch(OurCustomException e){
   assertEquals("Omg it failed, but not like we planned", FailureEnum.ZZZ, e.getFailure());
}
}

than:

@Test(expected = OurCustomException.class)
public void testDoSomethingFailsBecauseZzz() {
   doSomething();
}

when doSomethig () looks like this:

public void doSomething throws OurCustomException {
  if(Aaa) {
     throw OurCustomException(FailureEnum.AAA);
  } 
  if(Zzz) {
     throw OurCustomException(FailureEnum.ZZZ);
  }
  // ...
}

, , @Test (expected = blabla.class) (, , , ).

- /?

+5
6
  • , , expected.
  • (, ), .

, (, FailureEnum); try/catch.

, " try/catch" ( "" ), .

; . , , .:)

+5

, ? , , @Test(expected=XYZ.class) ?

+6

, expected. , - ( enum ), catch, . JUnit MethodRule. , API (ExpectedException), , enum s.

+2

(1), , (2), , .

. , :

@Test(expected = OurCustomException.class)
public void testDoSomethingFailsBecauseZzz() {
   try {
      doSomething();
   } catch (OurCustomException e) {
      if (e.getFailureEnum.equals(FailureEnum.ZZZ))  // use *your* method here
         throw e;

      fail("Catched OurCostomException with unexpected failure number: " 
        + e.getFailureEnum().getValue());  // again: your enum method here
   }
}

.

Edit

, : . , : , . , , .

+1

.

@Yishai, JUnit ExpectedException.

@Test(expected=SomeException.class) , .

ExpectedException:

@Test
public void testException()
{
    // If SomeException is thrown here, the test will fail.
    expectedException.expect(SomeException.class);
    // If SomeException is thrown here, the test will pass.
}

:

  • : ExpectedException.expectMessage();
  • : expectedException.expectCause().

: , / . (, , .)

+1

catch-exception, , , Stph. catch-exception :

@Test
public void testDoSomethingFailsBecauseZzz() {
   verifyException(myObj, OurCustomException.class).doSomething();
   assertEquals("Omg it failed, but not like we planned", FailureEnum.ZZZ,    
               ((OurCustomException)caughtException()).getFailure() ;
}
0

All Articles