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

前端 未结 30 1993
忘掉有多难
忘掉有多难 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 22:53

    In JUnit 4 or later you can test the exceptions as follows

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


    this provides a lot of features which can be used to improve our JUnit tests.
    If you see the below example I am testing 3 things on the exception.

    1. The Type of exception thrown
    2. The exception Message
    3. The cause of the exception


    public class MyTest {
    
        @Rule
        public ExpectedException exceptions = ExpectedException.none();
    
        ClassUnderTest classUnderTest;
    
        @Before
        public void setUp() throws Exception {
            classUnderTest = new ClassUnderTest();
        }
    
        @Test
        public void testAppleisSweetAndRed() throws Exception {
    
            exceptions.expect(Exception.class);
            exceptions.expectMessage("this is the exception message");
            exceptions.expectCause(Matchers.equalTo(exceptionCause));
    
            classUnderTest.methodUnderTest("param1", "param2");
        }
    
    }
    

提交回复
热议问题