How do you assert that a certain exception is thrown in JUnit 4 tests?

前端 未结 30 2554
忘掉有多难
忘掉有多难 2020-11-21 22:23

How can I use JUnit4 idiomatically to test that some code throws an exception?

While I can certainly do something like this:

@Test
public void testFo         


        
30条回答
  •  南旧
    南旧 (楼主)
    2020-11-21 23:15

    Update: JUnit5 has an improvement for exceptions testing: assertThrows.

    The following example is from: Junit 5 User Guide

     @Test
    void exceptionTesting() {
        Throwable exception = assertThrows(IllegalArgumentException.class, () -> 
        {
            throw new IllegalArgumentException("a message");
        });
        assertEquals("a message", exception.getMessage());
    }
    

    Original answer using JUnit 4.

    There are several ways to test that an exception is thrown. I have also discussed the below options in my post How to write great unit tests with JUnit

    Set the expected parameter @Test(expected = FileNotFoundException.class).

    @Test(expected = FileNotFoundException.class) 
    public void testReadFile() { 
        myClass.readFile("test.txt");
    }
    

    Using try catch

    public void testReadFile() { 
        try {
            myClass.readFile("test.txt");
            fail("Expected a FileNotFoundException to be thrown");
        } catch (FileNotFoundException e) {
            assertThat(e.getMessage(), is("The file test.txt does not exist!"));
        }
         
    }
    

    Testing with ExpectedException Rule.

    @Rule
    public ExpectedException thrown = ExpectedException.none();
    
    @Test
    public void testReadFile() throws FileNotFoundException {
        
        thrown.expect(FileNotFoundException.class);
        thrown.expectMessage(startsWith("The file test.txt"));
        myClass.readFile("test.txt");
    }
    

    You could read more about exceptions testing in JUnit4 wiki for Exception testing and bad.robot - Expecting Exceptions JUnit Rule.

提交回复
热议问题