前言
在项目中,有时候会把junit的注解@Test用在public static方法上报错,有时候会因为没有导入org.harmcrest.core.jar而引起错误,所以就来把junit整理一下。
使用步骤
1.导入junit的包。junit.jar和org.harmcrest.core.jar(注意:不要只导入junit-4.12的jar包,也要导入org.harmcrest.core.jar,不然会引起错误)
或者通过pom导入
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
2.在方法上添加@Test注解(注意:方法名称是public void xxx(){}的格式),举例:
@Test public void test() { ResourceBundle bundle = ResourceBundle.getBundle("jdbc"); String string = bundle.getString("pwd"); System.out.println(string); }
3.将鼠标光标移到想要执行的方法上,鼠标右键,选择run as --- Junit Test就可以啦,执行结果如下,如果是绿色就说明方法没问题,如果是红色查看原因进行排查,可能是方法的问题,也可能是junit的问题。
常见问题
1.method initializationerror not found
可能出现的原因:
- 有返回值的方法不能直接测试
- 带参数的方法不能直接测试
- 访问权限在public一下的方法不能直接测试
- static静态方法不能直接测试
- 不能给出现前四个条件中任意一个的方法添加@Test注解,否则执行满足@Test条件的方法也会出现initializationerror初始化异常