我想使用自定义TestExecutionListener
结合SpringJUnit4ClassRunner
在我的测试数据库上运行Liquibase架构设置。我的TestExecutionListener
工作正常,但是当我在我的类上使用注释时,被测试的DAO注入不再起作用,至少该实例为空。使用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);
}
}
}
有没有错误日志中,只是一个NullPointerException
在我的测试。我看不到如何使用我的TestExecutionListener
影响自动装配或注入。
这是正确的:如果你通过'@ TestExecutionListeners'指定了一个自定义的'TestExecutionListener',你隐式地覆盖了所有的默认TestExecutionListeners。当然,这个功能可能没有那么好记录。因此,请随时打开JIRA问题以请求对文档进行改进。 ;) –
@SamBrannen:实际上它被记录 - 也许有些含蓄。看到我更新的答案。 – nansen
我非常了解自你写作以来引用的文字。 ;)但是...没有明确描述你遇到的情况。这就是为什么我建议你打开JIRA票证来改进文档。 –