Spring整理系列(16)——通过单元测试理解spring容器以及dubbo+zookeeper单元测试异常处理


一、先说一个结论:单元测试与主项目的spring容器是隔离的,也就是说,单元测试无法访问主项目spring容器,需要自己加载spring容器。

接下来是代码实例,WEB主项目出于运行状态,单元测试中可能会看到如下这样的代码:

代码一:当前类加载式

public class TestSpring {
   

    @Test
    public void testSpring(){
        LoginService loginService = this.getBean("loginService");
    }

    //以下为容器实例声明及初始化、销毁
    private ClassPathXmlApplicationContext context;

    @Before
    public void before(){
        //加载spring容器
        context = new ClassPathXmlApplicationContext("spring-context.xml");
    }

    @After
    public void after(){
        context.destroy();
    }

    //从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
    public <T> T getBean(String name) {
        return (T) context.getBean(name);
    }

    //从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
    public <T> T getBean(Class<T> requiredType) {
        return context.getBean(requiredType);
    }
}

代码二:继承加载式

/** 
 * @Description: 登录单元测试类
 */
public class LoginTest extends SpringJunitSupport{
   

    @Autowired
    private LoginService loginService;

    @Test
    public void testLogin(){
        loginService.login();
    }
}
//让单元测试运行于spring环境,保证拥有spring框架相关支持
@RunWith(SpringJUnit4ClassRunner.class)
//加载spring容器
@ContextConfiguration("classpath:/spring-context.xml")
public class SpringJunitSupport {
   

}

代码三:动态添加spring配置文件式

/** 
 * @Description: 登录单元测试类
 */
public class LoginTest{
   

    //使用@Before注解方式加载spring容器配置文件,就不能通过自动装配的方式注入bean,因为自动装配注解执行要早于@Before
    //@Autowired
    private LoginService loginService;

    private TestSpringContextSupport springContextSupport = null;

    @Before
    public void setUp() throws Exception {
        springContextSupport = new TestSpringContextSupport();

        //初始化spring容器时,再动态添加spring bean配置文件
        springContextSupport.init(new String[] { "classpath:/support-quartz.xml" });
        loginService = springContextSupport.getBean("loginService");
    }

    @Test
    public void testLogin(){
        loginService.login();
    }
}
public class TestSpringContextSupport {

    //通过静态语句块初始化一个静态变量,用于存放spring容器配置文件
    public static List<String> contextList = new ArrayList<String>();
    static {
        contextList.add("classpath:/spring-context.xml");
    }

    private ApplicationContext context;

    //定义初始化方法,动态添加spring配置文件到静态配置文件集合
    public void init(String[] contextFile) {
        List<String> list = new ArrayList<String>();
        list.addAll(contextList);
        for (int i = 0; contextFile != null && i < contextFile.length; i+
  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值