简体   繁体   English

在JUnit中测试捕获的异常

[英]Testing Caught Exceptions in JUnit

I am trying to create a test that verifies that my code (see below for the pseudocode) correctly catches an exception. 我正在尝试创建一个测试来验证我的代码 (请参见下文的伪代码)正确捕获异常。 I know that JUnit is able to test whether the code throws an exception with the following code: 我知道JUnit可以使用以下代码测试代码是否引发异常:

@Test (expected = ArrayIndexOutOfBoundsException.class)

However, my original code of the software I'm testing catches this exception and prints a message 但是,我正在测试的软件的原始代码捕获了此异常并显示一条消息

catch (ArrayIndexOutOfBoundsException E) {
    System.out.print("The output should be of even length!");
}

Is there any way for JUnit to verify this message? JUnit有什么方法可以验证此消息? Or should I change something in my catch phrase? 还是应该更改流行语?

Note: I have read that I should use the following: 注意:我已阅读以下内容:

@Rule 
public ExpectedException thrown = ExpectedException.none();

@Test
public void decodeOddLengthInput() {
    thrown.expect(ArrayIndexOutOfBoundsException.class);
    thrown.expectMessage("Message");

But the program crashes because it doesn't recognize the ExpectedException object. 但是程序崩溃,因为它无法识别ExpectedException对象。

Pseudocode of the method I am trying to test (don't post the exact thing because of privacy reasons): 我尝试测试的方法的伪代码(由于隐私原因,请勿发布确切的内容):

public String decode(byte[] array){
try{
for(int i= 0; i<array.length; i= i+2){
//basically it crashes when input is an array of odd length (because of i=i+2)
   get byte at array[i] and turn it into a string;
   }
 }
catch (ArrayIndexOutOfBoundsException E) { System.out.print("Message!");}

  return string ;
  }

Your software method isn't re-throwing the exception with a message. 您的软件方法不会在消息中引发异常。 It is simply eating the exception by printing the message. 它只是通过打印消息来吃掉异常。 In this case, calling test method will never know about this exception, so you can not test this scenario or verify the message. 在这种情况下,调用测试方法将永远不会知道此异常,因此您无法测试此方案或验证消息。

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

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