使用SpringRunner执行junit的样例代码如下:
1 2 3 4 5 6 7 8 9 10 11 |
@RunWith(SpringRunner.class) @ContextConfiguration(locations={"/applicationContext.xml"}) public class XmlApplicationContextTest { @Autowired private HelloWorldService service; @Test public void test() { System.out.println( service.getHelloMessage()); } } |
被测试类上添加@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注解直接加载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@ContextConfiguration(locations={"/applicationContext.xml"}) public class XmlApplicationContextTest { @ClassRule public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule(); @Rule public final SpringMethodRule springMethodRule = new SpringMethodRule(); @Autowired private HelloWorldService service; @Test public void test() { System.out.println( service.getHelloMessage()); } } |
注意@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.