@runwith注解的作用
- @runwith就是一个运行器
- @runwith(junit4.class)就是指用junit4来运行
- @runwith(springjunit4classrunner.class),让测试运行于spring测试环境
- @runwith(suite.class)的话就是一套测试集合,
在使用 spring-test 的过程中,有两个 runner 可以选择,分别是 springrunner 和 springjunit4classrunner。
如果是在 4.3 之前,只能选择 springjunit4classrunner,如果是 4.3 之后,建议选择 springrunner。
springrunner 对 junit 的版本有要求,需要 4.12 及以上。
@runwith(springjunit4classrunner.class)使用了spring的springjunit4classrunner,以便在测试开始的时候自动创建spring的应用上下文。
其他的想创建spring容器的话,就得在web.xml配置classloder。
注解了@runwith就可以直接使用spring容器,直接使用@test注解,不用启动spring容器
@contextconfiguration
@contextconfiguration这个注解通常与@runwith(springjunit4classrunner.class)联合使用用来测试
当一个类添加了注解@component,那么他就自动变成了一个bean,就不需要再spring配置文件中显示的配置了。
把这些bean收集起来通常有两种方式,java的方式和xml的方式。
当这些bean收集起来之后,当我们想要在某个测试类使用@autowired注解来引入这些收集起来的bean时,只需要给这个测试类添加@contextconfiguration注解来标注我们想要导入这个测试类的某些bean。
@runwith(springjunit4classrunner.class) @contextconfiguration(locations = {"classpath*:/*.xml"}) public class cdplayertest { }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论