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

前端 未结 30 1996
忘掉有多难
忘掉有多难 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:59

    The most flexible and elegant answer for Junit 4 I found in the Mkyong blog. It has the flexibility of the try/catch using the @Rule annotation. I like this approach because you can read specific attributes of a customized exception.

    package com.mkyong;
    
    import com.mkyong.examples.CustomerService;
    import com.mkyong.examples.exception.NameNotFoundException;
    import org.junit.Rule;
    import org.junit.Test;
    import org.junit.rules.ExpectedException;
    
    import static org.hamcrest.CoreMatchers.containsString;
    import static org.hamcrest.CoreMatchers.is;
    import static org.hamcrest.Matchers.hasProperty;
    
    public class Exception3Test {
    
        @Rule
        public ExpectedException thrown = ExpectedException.none();
    
        @Test
        public void testNameNotFoundException() throws NameNotFoundException {
    
            //test specific type of exception
            thrown.expect(NameNotFoundException.class);
    
            //test message
            thrown.expectMessage(is("Name is empty!"));
    
            //test detail
            thrown.expect(hasProperty("errCode"));  //make sure getters n setters are defined.
            thrown.expect(hasProperty("errCode", is(666)));
    
            CustomerService cust = new CustomerService();
            cust.findByName("");
    
        }
    
    }
    

提交回复
热议问题