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

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

    Just make a Matcher that can be turned off and on, like this:

    public class ExceptionMatcher extends BaseMatcher {
        private boolean active = true;
        private Class throwable;
    
        public ExceptionMatcher(Class throwable) {
            this.throwable = throwable;
        }
    
        public void on() {
            this.active = true;
        }
    
        public void off() {
            this.active = false;
        }
    
        @Override
        public boolean matches(Object object) {
            return active && throwable.isAssignableFrom(object.getClass());
        }
    
        @Override
        public void describeTo(Description description) {
            description.appendText("not the covered exception type");
        }
    }
    

    To use it:

    add public ExpectedException exception = ExpectedException.none();, then:

    ExceptionMatcher exMatch = new ExceptionMatcher(MyException.class);
    exception.expect(exMatch);
    someObject.somethingThatThrowsMyException();
    exMatch.off();
    

提交回复
热议问题