JUnit: successful test if an exception is thrown

Is it possible that the JUnit test will succeed if it returns the expected exception?

Can you tell me how to implement such a test with a simplified example?

Many thanks.

+4
source share
3 answers

Why can't you just catch your exception in the test? There are different ways to do this. Like annotations @Test(expected = DataAccessException.class), and it also needs to be used on a case-by-case basis. But below is what I suggest.

public class TestCase{
    @Test
    public void method1_test_expectException () {
     try{
     // invoke the method under test...
     Assert.fail("Should have thrown an exception"); 
     // This above line would only be reached if it doesnt throw an exception thus failing your test. 
                }
     catch(<your expected exception> e){
       Assert.assertEquals(e.getcode(), somce error code);
     }
 }

Several advantages using this approach.

  • If you have your own exception with an error code, you can argue for an error code. So tighten your test.
  • , . ( , , . .)
+6

JUnit4 , ExpectedException, @Rule,

import org.junit.rules.ExpectedException;
import org.junit.Rule;
import org.junit.Test;


public class MyTestClass {
  @Rule 
  public ExpectedException thrown = ExpectedException.none();

  @Test
  public void aTestThatSucceedsOnlyIfRuntimeExceptionIsThrown() {
      thrown.expect(RuntimeException.class);  
      // invoke code to be tested...
  }
}

, @Test(expected=RuntimeException.class), : , . , , ( ), , .

+3

:

public class SimpleDateFormatExampleTest {

    @SuppressWarnings("deprecation")
    @Test(expected=ParseException.class)
    public void testConvertStringToDate() throws ParseException {
        SimpleDateFormatExample simpleDateFormatExample = new SimpleDateFormatExample();

    Assert.assertNotNull(simpleDateFormatExample.convertStringToDate("08-16-2011"));

(expected=ParseException.class)

Assert.assertNotNull(simpleDateFormatExample.convertStringToDate("08/16/2011"));

    }

public class SimpleDateFormatExample {


    public Date convertStringToDate(String dateStr) throws ParseException{
        return new SimpleDateFormat("mm/DD/yyyy").parse(dateStr);
    }
}
0

All Articles