Spring单元测试类

public class UnitTestBase {
        private ClassPathXmlApplicationContext context;
	private String springXmlpath;//spring的xml文件路径
	
	public UnitTestBase() {}
	
	public UnitTestBase(String springXmlpath) {
		this.springXmlpath = springXmlpath;
	}
	
	//在Test方法执行前执行
	@Before
	public void before(){
		if(StringUtils.isEmpty(springXmlpath)){
			springXmlpath = "classpath*:spring-*.xml";
		}
		try{
			//spring容器
			context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+"));
			//split()切割掉所有,逗号 任何空白字符 +匹配前面表达式一次或多次
			context.start();
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	//在Test方法执行后执行
	@After
	public void after(){
		context.destroy();//销毁
	}
	
	@SuppressWarnings("unchecked")//忽略unchecked警告信息
	protected <T extends Object> T getBean(String beanId){
		try {
			return (T)context.getBean(beanId);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}
	
	protected <T extends Object> T getBean(Class<T> clazz){
		try {
			return (T)context.getBean(clazz);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}
	
}


@Scope("prototype")
@Component
public class BeanAnnotation {
	
	public void say(String str){
		System.out.println("BeanAnnotation:"+str);
	}
	public void myHashCode(){
		System.out.println("BeanAnnotation:"+this.hashCode());
	}
}

@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanAnnotation extends UnitTestBase{
	public TestBeanAnnotation(){
		super("classpath*:spring-beanannotation.xml");
            //super("classpath*:spring-beanannotation.xml");
}@Testpublic void testSay(){BeanAnnotation bean = super.getBean("beanAnnotation");bean.say("this is test.");}@Testpublic void testScope(){//测试Scope()注解的作用域prototype,每次有请求的时候,都会创建一个对象BeanAnnotation bean = super.getBean("beanAnnotation");bean.myHashCode();bean = super.getBean("beanAnnotation");bean.myHashCode();}} Spring可以通过指定classpath*:与classpath:前缀加路径的方式从classpath加载文件,如bean的定义文件classpath*:的出现是为了从多个jar文件中加载相同的文件classpath:只能加载找到的第一个文件.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值