「Springのテストで気になること - あしのあしあと」の内容は、解決できず。進展があったら、追記しようと思う。
で、テストコードは、いったん、次にした。
package hello; import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/test-applicationContext.xml") public class HelloMessagePrinterTest { @Autowired ApplicationContext context; @Test public void test_getMessage() { MessagePrinter printer = (MessagePrinter) context.getBean("messagePrinter"); assertEquals("Hello World!", printer.getMessage()); } @Test public void test_getMessage2() { HelloMessageData.setMessage("Nice to meet you!"); refreshContext(); MessagePrinter printer = (MessagePrinter) context.getBean("messagePrinter"); assertEquals("Nice to meet you!", printer.getMessage()); } @Test public void test_getMessage3() { HelloMessageData.setMessage("What's your Name?"); refreshContext(); MessagePrinter printer = (MessagePrinter) context.getBean("messagePrinter"); assertEquals("What's your Name?", printer.getMessage()); } private void refreshContext() { context = new ClassPathXmlApplicationContext("test-applicationContext.xml"); } }
@DirtiesContext
アノテーションを使ってみたが、アプリケーションコンテキストのリフレッシュのタイミングがメソッド実行の後になってしまい、自由にタイミングがはかれないため、実現できなかった。
When an application context is marked dirty, it is removed from the testing framework’s cache and closed. As a consequence, the underlying Spring container will be rebuilt for any subsequent test that requires a context with the same configuration metadata.
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#integration-testing-annotations-spring
また、ConfigurableApplicationContext#refresh
メソッドも試してみたが、そもそも使う場面が違うっぽくて、うまくいかなかった。
やっぱ、きちんと内部の動作を知るべきだよなぁ。
しかも、まだあるんだよなぁ、わからないことが。