What's the actual use of 'fail' in JUnit test case?

后端 未结 8 1130
长情又很酷
长情又很酷 2021-01-30 15:31

What\'s the actual use of \'fail\' in JUnit test case?

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-30 16:10

    Some cases where I have found it useful:

    • mark a test that is incomplete, so it fails and warns you until you can finish it
    • making sure an exception is thrown:
    try{
      // do stuff...
      fail("Exception not thrown");
    }catch(Exception e){
      assertTrue(e.hasSomeFlag());
    }
    

    Note:

    Since JUnit4, there is a more elegant way to test that an exception is being thrown: Use the annotation @Test(expected=IndexOutOfBoundsException.class)

    However, this won't work if you also want to inspect the exception, then you still need fail().

提交回复
热议问题