我正在尝试创建一个测试来验证我的代码(请参阅下面的伪代码)是否正确捕获异常。我知道JUnit可以用下面的代码来测试代码是否抛出异常:
@Test (expected = ArrayIndexOutOfBoundsException.class)
但是,我正在测试的软件的原始代码捕获了此异常并打印一条消息
catch (ArrayIndexOutOfBoundsException E) {
System.out.print("The output should be of even length!");
}
JUnit 有什么方法可以验证这个消息吗?或者我应该改变我的口号中的一些内容?
注意:我已读到我应该使用以下内容:
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void decodeOddLengthInput() {
thrown.expect(ArrayIndexOutOfBoundsException.class);
thrown.expectMessage("Message");
但是程序崩溃了,因为它无法识别
ExpectedException
对象。
我尝试测试的方法的伪代码(由于隐私原因,请勿发布确切的内容):
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 ;
}
您的软件方法不会通过消息重新抛出异常。它只是通过打印消息来吃掉异常。在这种情况下,调用测试方法将永远不会知道此异常,因此您无法测试此场景或验证消息。
使用 Junit5 现在可以断言返回异常的方法,如下所示:
import org.junit.jupiter.api.Assertions;
class YourServiceImplTest {
private YourService subject;
@Test
public void decodeOddLengthInput() {
// Act and Assert
Assertions.assertThrows(YourException.class, () -> {
subject.getAll();
}, "Error message expected");
}
}