このようなユースケースでは、いつでもプログラムでコンテキストを開始できます。この場合、コンテキストのライフサイクルを担当していることに注意してください。次の擬似コードはこれを示しています。
@Test
public void yourTest() {
// setup your database
ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext("/org/foo/your-context.xml");
// Or new AnnotationConfigApplicationContext(YourConfig.class)
try {
YourBean bean = context.getBean("beanId");
// Assertions
} finally {
context.close();
}
}
データベースを初期化するには、おそらく Spring が必要です。たとえば、通常の Spring テスト コンテキスト サポートを使用して、データベースのセットアップに必要な Bean のみを初期化し、プログラムで別のコンテキストを開始してサービスをアサートすることができます。そのコンテキストがデータベースの初期化に使用されたいくつかのサービスを必要とする場合は、代わりに次のような子コンテキストを開始できます。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration // for instance FooTest-context.xml
public class FooTest {
@Autowired
private ApplicationContext mainContext;
@Test
public void yourTest() {
// setup your database
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext();
context.setParent(mainContext);
context.setConfigLocation("/org/foo/your-context.xml");
context.refresh();
try {
YourBean bean = context.getBean("beanId");
// Assertions
} finally {
context.close();
}
}
}
これが繰り返し使用される場合は、コンテナーを開始してコールバック インターフェイスを呼び出すテンプレート メソッドを作成できます。そうすれば、コンテキストのライフサイクル管理を一元的に共有できます。