カスタムTestExecutionListener
とSpringJUnit4ClassRunner
を組み合わせて、テストデータベースでLiquibaseスキーマのセットアップを実行します。私のTestExecutionListener
はうまくいきますが、私のクラスで注釈を使用すると、テスト中のDAOの注入が機能しなくなりました。少なくともインスタンスはnullです。TestExecutionListenerを使用しているときにSpringテスト注入が機能しない
@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
の使用がautowiringまたは注入にどのように影響するかはわかりません。
それは正しいです: '@ TestExecutionListeners'を介してカスタム' TestExecutionListener'を指定すると、デフォルトのTestExecutionListenersのすべてが暗黙的にオーバーライドされます。確かに、この機能はあまりよく書かれていません。ですから、JIRAの問題を開いてドキュメントの改善を要請してください。 ;) –
@SamBrannen:実際にはそれは文書化されています。私の更新された答えを見てください。 – nansen
私はそれを書いて以来、あなたが引用したテキストをよく知っています。 ;)しかし、それはあなたが遭遇したシナリオを明示的に記述していません。そのため、ドキュメントを改善するためにJIRAチケットを開くことをお勧めしました。 –