Spring学习之旅(1)——单元测试
单元测试的包: junit-4.10.jar
(1) 创建UnitTestBean类,所有的测试类都继承它, 通过getBean获取对象
ClassPathXmlApplicationContext 上下文
springXmlpath spring bean 配置文件
通过构造函数加载bean 配置文件
before() 在test类执行前执行 将配置文件加载到context;
getBean(String beanId) beanid 是在spring bean 配置文件中<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 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;
}
}
}
测试子类:
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配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd" >
<!-- bean在spring中的配置
bean id = "oneInterface" class="实现类”
-->
<bean id="oneInterface" class="com.chb.ioc.interfaces.OneInterfaceImpl"></bean>
</beans>