单元测试中,针对接口的测试是必须的,但是如何非常方便的获取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。