简体   繁体   English

测试Junit是否捕获到异常

[英]Test if an exception is caught with Junit

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. 在此函数中,数据包被打开,并且当它不包含所有预期数据时,将引发InvalidParameterExeption并记录下来。

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? 如何测试抛出InvalidParameterExeption?

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);
}

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
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM