为了账号安全,请及时绑定邮箱和手机立即绑定

Spring 中引入单元测试

标签:
Java

Spring 中引入单元测试
操作步骤

  1. 下载 junit-*.jar 并引入项目中。
  2. 创建 UnitTestBase 类,完成对 Spring 配置文件的加载、销毁
  3. 所有的单元测试类都继承 UnitTestBase,通过它的 getBean 方法获取想要得到的对象
  4. 子类(具体执行单元测试的类)加注解:@RunWith(BlockJUnit4ClassRunner.class)
  5. 单元测试方法加注解:@Test
  6. 右键执行

UnitTestBase 类(加载 spring.xml 配置文件)

package com.imooc.test.base;

import org.junit.After;
import org.junit.Before;
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;

public class UnitTestBase {

    private ClassPathXmlApplicationContext context;

//    springxml的路径
    private String springXmlpath;

    public UnitTestBase() {}

//    构造器传入路径,子类构造器传入具体路径
    public UnitTestBase(String springXmlpath) {
        this.springXmlpath = springXmlpath;
    }

//    执行顺序 @Before -- @Test -- @After
    @Before
    public void before() {
//        判空处理
        if (StringUtils.isEmpty(springXmlpath)) {
            springXmlpath = "classpath*:spring-*.xml";
        }
        try {
//            上下文,Spring的容器
//            查找配置文件中的配置信息,加载信息到context中,获取信息时使用context.getBean(String id)方法获取相应对象
            context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+"));
            context.start();
        } catch (BeansException e) {
            e.printStackTrace();
        }
    }

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

//    context的bean方法
    @SuppressWarnings("unchecked")
    protected <T extends Object> T getBean(String beanId) {
        try {
            return (T)context.getBean(beanId);
        } catch (BeansException e) {
            e.printStackTrace();
            return null;
        }
    }

    protected <T extends Object> T getBean(Class<T> clazz) {
        try {
            return context.getBean(clazz);
        } catch (BeansException e) {
            e.printStackTrace();
            return null;
        }
    }

}

注意:

  • springxml为配置文件路径,构造器传入路径,子类构造器传入具体路径

  • 执行顺序 @Before -- @Test -- @After
  • @Before 中查找并加载配置信息,存放于 Spring 的容器 context 中,使用context.getBean获取相应对象。
  • @Test 子类中需要测试的方法
  • @After 关闭context
点击查看更多内容
7人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消