Test if an exception is caught with Junit

半腔热情 提交于 2019-12-23 20:22:49

问题


I'll begin with a code example; I have to test a function, which handles data-packets. In this function, the data-packet is opened and when it doesn't contain all expected data, an InvalidParameterExeption is thrown which is logged.

public void handleData(dataPacket) {
    try {
        analyseData(dataPacket);
    } catch (InvalidParameterException e) {
        e.printStackTrace()
    }
}

So, if everything goes well, my exception is printed in my terminal. But how can I test this? I can't use this: (because the exception is caught)

@Test(expected = InvalidParameterExeption.class)
public void testIfFaultyDataPacketIsRecognised {
    handleData(faultyDataPacket);
}

How can I test that the InvalidParameterExeption is thrown?


回答1:


you wont catch exceptions that are not thrown -_- just test the 'throwing exception method' instead of the 'exception catching' one

@Test(expected = InvalidParameterExeption.class)
public void testIfFaultyDataPacketIsRecognised() {
    analyseData(faultyDataPacket);
}



回答2:


Ideally you should catch and rethrow the exception.But if you dont want to do that then Why not get catch the exception in test case as expected?

@Test
public void testIfFaultyDataPacketIsRecognised () {
  try {
      handleData(faultyDataPacket);
      Assert.fail("Fail! Method was expected to throw an exception because faulty data packet was sent.")
  } catch (InvalidParameterException e) {
      // expected
  }
}


来源:https://stackoverflow.com/questions/40676860/test-if-an-exception-is-caught-with-junit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!