這是本文件的舊版!


Spring In JUnit HelloWorld!

在寫這篇文章前,我只使用Spring Test去測試過我們的REST API。某一日,因為看到同事誤用的@ActiveProfile,讓我發現了其它不錯的Test Annotation。本篇文章分享給大家一些基本寫法。

下面這段是在修改之前的Load與Close Spring Context的程式碼,會註冊兩個Config,並將我們需要的物件綁定到此TestCase物件上:

private AnnotationConfigApplicationContext springContext;
@Before
public void setup(){
	springContext = new AnnotationConfigApplicationContext();
	springContext.setEnvironment(env);
	springContext.register(
			ModelConfig.class,
			MockConfig.class
	);
 
	springContext.refresh();
 
	springContext.getAutowireCapableBeanFactory().autowireBean(this);
}
 
@After
public void teardown(){
	springContext.close();
}
上面冗長的程式碼,只要使用以下Annotation,就可以達到Load與Close:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes={ModelConfig.class, MyTest.MockConfig.class})
public class RedfishSpringConfigTest {
	// skip
}
Runner要使用SpringRunner,而ContextConfiguration可以指定你要載入的Config class;假如你的config是xml形式,可以使用下面的寫法讓它去你的classpath找設定檔:
@ContextConfiguration("myconfig.xml")

在執行測試過程中,一定會需要從Spring Context中取得你需要的Bean進行測試,以下是舊的寫法:

AppController controller = springContext.getBean(AppController.class);
在透過SpringRunner執行測試案例後,你可以直接在測試案例中綁定資源,以下是@Autowired寫法:
@Autowired
private AppController appController;