1.
package com.wuyonghu.junit;
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 {
// 这个context就是上下文容器
private ClassPathXmlApplicationContext context;
private String springXmlpath;
public UnitTestBase() {
};
public UnitTestBase(String springXmlpath) {
//传入的参数就是spring配置bean的配置文件的路径
this.springXmlpath = springXmlpath;
}
@Before
public void before() {
//如果为空时候的处理方式
if (StringUtils.isEmpty(springXmlpath)) {
springXmlpath = "classpath*:spring-*.xml";
}
try {
context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+"));
// 装载bean:将配置文件中的bean加载到context上下文中
context.start();
} catch (BeansException e) {
e.printStackTrace();
}
}
@After
public void after() {
context.destroy();
}
@SuppressWarnings("unchecked")
protected <T extends Object> T getBean(String beanId) {
// 获取到上下文中的bean的方法
return (T) context.getBean(beanId);
}
protected <T extends Object> T getBean(Class<T> clazz) {
// 获取到上下文中的bean的方法
return (T) context.getBean(clazz);
}
}
2.配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<bean id="oneInterface" class="com.wuyonghu.faceinterface.OneInterfaceImple"></bean>
</beans>
3.测试代码:
package com.wuyonghu.faceinterface;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import com.wuyonghu.junit.UnitTestBase;
@RunWith(BlockJUnit4ClassRunner.class)
public class ConfigTest extends UnitTestBase{
public ConfigTest(){
super("classpath*:applicationContext.xml");
}
@Test
public void testHello(){
OneInterface oneInterface=super.getBean("oneInterface");
System.out.println(oneInterface.hello("单元测试"));
}
}
以上使用到的是通過继承的方法,如果难以理解则可以直接这样:
@Test
public void testHello2() {
//获取到bean容器,其中applicationContext.xml就是spring配置文件
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
//通过getBean方法从上下文中获取到bean对象
OneInterface bean = (OneInterface) context.getBean("oneInterface");
System.out.println(bean.hello("classpath方式获取"));
}