在junit测试框架里我们已经有了几个常见的注解来定义test case执行前后的回调行为。
注释 | 说明 |
@Before | 初始化方法 |
@After | 释放资源 |
@Test | 测试方法 |
@Ignore | 忽略的测试方法 |
@BeforeClass | 针对所有测试,只执行一次,且必须为static void |
@AfterClass | 针对所有测试,只执行一次,且必须为static void |
这些方法可以满足大多数应用的需求。但是Spring中也集成了Unit测试的功能,并且同样定义了一些回调函数可以切入。
下面记录下项目中的一个应用实例。
Dao的测试里需要在每个测试方法之前都对相应的数据库数据进行初始化。因为测试数据不是通过数据标示来区分不同case的。所以每次case测试前只要将本case的数据初始化。这样一来在测试方法开始之前,必须得到这个要测试的方法名。Junit的注解中@Before是在每个方法开始之前运行的,但是在里面无法得到即将要测试的方法名。Junit没有提供相应的机制给出测试中的流程数据。
这时我们就可以借助Spring提供的@TestExecutionListeners来插入这种回调。
class BeforeMethod implements TestExecutionListener {
public static final Logger logger = Logger.getLogger(BeforeMethod.class);
@Override
public void afterTestClass(TestContext arg0) throws Exception {
}
@Override
public void afterTestMethod(TestContext arg0) throws Exception {
}
@Override
public void beforeTestClass(TestContext arg0) throws Exception {
}
@Override
public void beforeTestMethod(TestContext con) throws Exception {
String testClass = con.getTestClass().getSimpleName();
logger.debug("database initialization class name: " + testClass);
String testMethod = con.getTestMethod().getName();
logger.debug("database initialization method name: " + testMethod);
DBInitializer.doInit(testClass, testMethod);
}
@Override
public void prepareTestInstance(TestContext arg0) throws Exception {
}
}
TestContext 核心类、支持类以及注解类
TestContext 测试框架的核心由 org.springframework.test.context 包中三个类组成,分别是 TestContext 和 TestContextManager 类以及 TestExecutionListener 接口。
1.TestContext:它封装了运行测试用例的上下文;
2.TestContextManager:它是进入 Spring TestContext 框架的程序主入口,它管理着一个 TestContext 实例,并在适合的执行点上向所有注册在 TestContextManager 中的 TestExecutionListener 监听器发布事件:比如测试用例实例的准备,测试方法执行前后方法的调用等。
3.TestExecutionListener:该接口负责响应 TestContextManager 发布的事件。
Spring TestContext 允许在测试用例类中通过 @TestExecutionListeners 注解向 TestContextManager 注册多个监听器,如下所示:
|
DependencyInjectionTestExecutionListener:该监听器提供了自动注入的功能,它负责解析测试用例中 @Autowried 注解并完成自动注入。
在 JUnit中可以通过 @RunWith 注解指定测试用例的运行器,Spring TestContext 框架提供了SpringJUnit4ClassRunner 运行器,它负责总装 Spring TestContext 测试框架并将其统一到 JUnit框架中。
最终监听器类和TestContext的使用通过在Test类上的注解来定义
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
@TestExecutionListeners({ BeforeMethod.class, DependencyInjectionTestExecutionListener.class })
public class DaoTestBase {
}