SpringRunner及SpringTestRule的源码分析

2月 10, 2018 |

使用SpringRunner执行junit

使用SpringRunner执行junit的样例代码如下:

被测试类上添加@RunWith(SpringRunner.class) 指定要使用的Runner,@ContextConfiguration指定上下文的初始化源, 是从xml文件还是从@Configuration注解的类加载
注入待测试的类如上例中的HelloWorldService, 在@Test注解的方法就可以使用该注入的类。
本文由javacoder.cn整理,转载注明出处
各个步骤的序列图如下所示

如下方法实现了上下文加载的逻辑
public final org.springframework.test.context.support.AbstractTestContextBootstrapper buildMergedContextConfiguration()
归纳如下:
1)如果测试类没有ContextConfiguration及ContextHierarchy注解,xml为被测试的classname+"-context.xml"后缀,annotation方式为使用@Configuration注解的内部静态类
2)如果有@ContextHierarchy注解,按照层级合并后加载
3)只有@ContextConfiguration注解直接加载

使用JUnit4默认的Runner配合spring定制的Rule

注意@ClassRule注解必须作用在static public的属性上, @Rule必须作用在public的成员属性上
如下方法是分别插入@ClassRule和@Rule注解的入口
org.junit.runners.ParentRunner.classBlock(RunNotifier notifier)
org.junit.runners.BlockJUnit4ClassRunner.methodBlock(FrameworkMethod method)

Posted in: java基础

Comments are closed.