使用 TestExecutionListener 时,弹簧测试注射不起作用
2022-09-03 12:27:25
我想结合使用自定义,在我的测试数据库上运行 Liquibase 架构设置。我的工作正常,但是当我对我的类使用注释时,测试中DAO的注入不再有效,至少实例为空。TestExecutionListener
SpringJUnit4ClassRunner
TestExecutionListener
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/applicationContext-test.xml" })
@TestExecutionListeners({ LiquibaseTestExecutionListener.class })
@LiquibaseChangeSet(changeSetLocations={"liquibase/v001/createTables.xml"})
public class DeviceDAOTest {
...
@Inject
DeviceDAO deviceDAO;
@Test
public void findByCategory_categoryHasSubCategories_returnsAllDescendantsDevices() {
List<Device> devices = deviceDAO.findByCategory(1); // deviceDAO null -> NPE
...
}
}
监听器相当简单:
public class LiquibaseTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
final LiquibaseChangeSet annotation = AnnotationUtils.findAnnotation(testContext.getTestClass(),
LiquibaseChangeSet.class);
if (annotation != null) {
executeChangesets(testContext, annotation.changeSetLocations());
}
}
private void executeChangesets(TestContext testContext, String[] changeSetLocation) throws SQLException,
LiquibaseException {
for (String location : changeSetLocation) {
DataSource datasource = testContext.getApplicationContext().getBean(DataSource.class);
DatabaseConnection database = new JdbcConnection(datasource.getConnection());
Liquibase liquibase = new Liquibase(location, new FileSystemResourceAccessor(), database);
liquibase.update(null);
}
}
}
日志中没有错误,只是我的测试中有一个错误。我不明白使用 my 如何影响自动布线或注入。NullPointerException
TestExecutionListener