测试Junit是否捕获到异常

测试Junit是否捕获到异常

本文介绍了测试Junit是否捕获到异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将以一个代码示例开始;我必须测试一个处理数据包的功能.在此函数中,数据包被打开,并且当它不包含所有预期数据时,将引发InvalidParameterExeption并记录下来.

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

如何测试是否抛出了InvalidParameterExeption?

How can I test that the InvalidParameterExeption is thrown?

推荐答案

您不会捕获未引发的异常-_-只需测试抛出异常方法"而不是异常捕获"方法

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

这篇关于测试Junit是否捕获到异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 14:02