單元測試中,針對接口的測試是必須的,但是如何非常方便的獲取Spring注冊的Bean呢?
如果可以獲取所有的Bean,這樣就可以將這個方法放到基類中,方便后面所有單元測試類的使用,具體實現如下:
1 import org.apache.log4j.Logger; 2 import org.junit.AfterClass; 3 import org.junit.Before; 4 import org.junit.BeforeClass; 5 import org.springframework.beans.factory.support.DefaultListableBeanFactory; 6 import org.springframework.context.ApplicationContext; 7 import org.springframework.context.support.ClassPathXmlApplicationContext; 8 9 public abstract class BaseTest { 10 protected Logger log = Logger.getLogger(this.getClass()); 11 protected static ApplicationContext appContext; 12 13 @BeforeClass 14 public static void setUp() throws Exception { 15 try { 16 long start = System.currentTimeMillis(); 17 System.out.println("正在加載配置文件..."); 18 19 appContext = new ClassPathXmlApplicationContext(new String[]{"spring-config.xml","spring-config-struts.xml"}); 20 21 System.out.println("配置文件加載完畢,耗時:" + (System.currentTimeMillis() - start)); 22 } catch (Exception e) { 23 e.printStackTrace(); 24 } 25 } 26 27 public static void main(String[] args) { 28 System.out.println(BaseTest.class.getResource("/")); 29 } 30 31 protected boolean setProtected() { 32 return false; 33 } 34 35 @Before 36 public void autoSetBean() { 37 appContext.getAutowireCapableBeanFactory().autowireBeanProperties(this, DefaultListableBeanFactory.AUTOWIRE_BY_NAME, false); 38 } 39 40 @AfterClass 41 public static void tearDown() throws Exception { 42 } 43 }
這樣后面單元測試的類就可以繼承自該類來使用,方便快捷。
獲取Spring下所有Bean的關鍵在於首先指定Spring配置文件的路徑:
ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[]{"spring config path"});
然后通過appContext來獲取注入的Bean:
appContext.getAutowireCapableBeanFactory().autowireBeanProperties(this, DefaultListableBeanFactory.AUTOWIRE_BY_NAME, false);
當然這里需要利用JUnit的@Before,在執行前操作獲取Bean。