【单元测试】SpringRunner执行原理

 

https://zhuanlan.zhihu.com/p/571520010

 

 SpringRunner实现Junit暴露的BlockJUnit4ClassRunner

 

 

SpringJUnit4ClassRunner实现了BlockJUnit4ClassRunner,它运行的是一个标准的JUnit4测试模型。

SpringJUnit4ClassRunner则是在此基础上做了一些扩展,扩展的内容主要包括:

  l  扩展了构造函数,多创建了一个TestContextManager实例。

  l  扩展了createTest()方法,会额外调用TestContextManager的prepareTestInstance方法。

  l  扩展了beforeClass,在执行@BeforeClass注解的方法前,会先调用TestContextManager的beforeTestClass方法。

  l  扩展了before,在执行@Before注解的方法前,会先调用TestContextManager的beforeTestMethod方法。

  l  扩展了afterClass,在执行@AfterClass注解的方法之后,会再调用TestContextManager的afterTestClass方法。

  l  扩展了after,在执行@After注解的方法之后,会再调用TestContextManager的after方法。

 

包含的TestContextManager

1、管理TestContext

  TestContext:对ApplicationContext的一个再封装,可以把TestContext理解为增加了测试相关功能的Spring容器。在DefaultTestContext的getApplicationContext方法中,调用了  cacheAwareContextLoaderDelegate的loadContext,最终辗转调到Context的refresh方法,从而构筑起Spring容器上下文

2、管理TestExecutionListeners

  使用观察者模式提供了对测试运行过程中的关键节点(如beforeClass, afterClass等)的监听能力。

 

posted @ 2022-12-31 21:10  飞翔在天  阅读(425)  评论(0编辑  收藏  举报