您当前的位置: 首页 >  单元测试

宝哥大数据

暂无认证

  • 1浏览

    0关注

    1029博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Spring学习之旅(1)------单元测试

宝哥大数据 发布时间:2016-08-01 08:20:03 ,浏览量:1

Spring学习之旅(1)——单元测试

单元测试的包: junit-4.10.jar   (1) 创建UnitTestBean类,所有的测试类都继承它, 通过getBean获取对象     ClassPathXmlApplicationContext 上下文      springXmlpath spring bean 配置文件     通过构造函数加载bean 配置文件     before() 在test类执行前执行 将配置文件加载到context;     getBean(String beanId) beanid 是在spring bean 配置文件中中定义的id     after() 在test执行之后,注销context;

  (2) 测试子类 继承UnitTestBean     (1)子类加注解@RunWith(BlockJUnit4ClassRunner.class)     (2)单元测试方法加注解@Test

  (3) 执行测试方法:右键选择要测试的单元测试方法执行

UnitTestBase.java
package com.chb.test.base.ioc;

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;

    private String springXmlpath;

    public UnitTestBase() {}

    public UnitTestBase(String springXmlpath) {
        this.springXmlpath = springXmlpath;
    }

    @Before
    public void before() {
        if (StringUtils.isEmpty(springXmlpath)) {
            springXmlpath = "classpath*:spring-*.xml";
        }
        try {
            context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+"));
            context.start();
        } catch (BeansException e) {
            e.printStackTrace();
        }
    }

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

    @SuppressWarnings("unchecked")
    protected  T getBean(String beanId) {
        try {
            return (T)context.getBean(beanId);
        } catch (BeansException e) {
            e.printStackTrace();
            return null;
        }
    }

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

}
测试子类:
package com.chb.test.ioc.interfaces;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

import com.chb.ioc.interfaces.OneInterface;
import com.chb.test.base.ioc.UnitTestBase;

@RunWith(BlockJUnit4ClassRunner.class)
public class TestOneInterface extends UnitTestBase{
    public TestOneInterface() {
        super("classpath*:spring-ioc.xml");
    }

    @Test
    public void testHello() {
        OneInterface oif = super.getBean("oneInterface");
        oif.say("美女");
    }
}
Bean配置文件


    
    

 

     这里写图片描述

关注
打赏
1587549273
查看更多评论
立即登录/注册

微信扫码登录

0.0396s