环境:Junit 4.12
依赖注入: <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>下面给出一个例子:
/**实例函数:当输入的数字不是正数时,则抛出异常。**/ public int inputPositiveNumber(int a){ if(a<=0) throw new new IllegalArgumentException("This is not a positive number"); else return; } @Test public void testThrown(){ /*测试函数*/ try{ inputPositiveNumber(-1); }catch(IllegalArgumentException i){ assertEquals(i.getMessage(),"This is not a positive number"); } }总结:通过对异常进行catch捕获,然后提取出异常中的内容信息,使用assertEquals()函数进行异常内容信息的匹配,从而达到对抛出异常的精准定位。
模板:
try{ //需要测试的代码; }catch(ExceptionName exceptionName){ assertEquals(exceptionName.getMessage(), "抛出异常的具体信息"); }