Try catch in a JUnit test

前端 未结 7 584
悲哀的现实
悲哀的现实 2020-12-04 23:21

I\'m writing unit tests for an application that already exists for a long time. Some of the methods I need to test are build like this:

public void someMetho         


        
7条回答
  •  庸人自扰
    2020-12-04 23:52

    @Test
    public void someTest() {
       try {
         someMethod();
       }
       catch (Exception e) {
         Assert.fail("Exception " + e);
       }
    }
    

    Is what you can do, if the exception should not occur. An alternative would be to throw the exception in the signature like this:

    @Test
    public void someTest() throws Exception {
         someMethod();
    }
    

    The difference is, that in one case the test will fail with an assertion exception and in the other case it will fail because the test crashed. (like somewhere in your code you get a NPE and the test will because of that)

    The reason you have to do this, is because Exception is a checked exception. See Checked versus unchecked exception

    The @Test(expected=Exception.class) is for tests, that want to test that the exception will be thrown.

    @Test(expected=ArrayIndexOutOfBounds.class)
    public void testIndex() {
       int[] array = new int[0];
       int var = array[0]; //exception will be thrown here, but test will be green, because we expect this exception
    
    }
    

提交回复
热议问题