JUnit right way of test expected exceptions

后端 未结 4 1097
走了就别回头了
走了就别回头了 2020-12-15 20:37

Hello guys I was wondering if this way of testing my exception is ok, i have this exception i need to throw in the second test annotation, im receiving as result a red evil

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-15 21:09

    You can use ExpectedException which can provide you more precise information about the exception expected to be thrown with the ability to verify error message, as follows:

    import org.junit.Rule;
    import org.junit.Test;
    import org.junit.rules.ExpectedException;
    import org.junit.runner.RunWith;
    public class TestClass {
    
        @Rule
        public ExpectedException expectedException = ExpectedException.none();
    
    
        @Test
        public void GTFRICreationTester_shouldFail()  {
            expectedException.expect(TramaConProtolocoloDesconocido.class);
            factory.createLocomotive(weirdProtocol, false, new Date());
        }
    }
    

    To expolore more about it, you can refer to the blog written by me here - Expected Exception Rule and Mocking Static Methods – JUnit

提交回复
热议问题