首先介绍一下UnitTestBase这是自己定义的一个类并不是Spring 框架带的,他的作用是为了单元测试的。你准备的类要继承他 先把代码发出来:
import org.junit.After;
import org.junit.Before;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;
public class UnitTestBase {
private ClassPathXmlApplicationContext context;
private String stringXmlPath;
public UnitTestBase() {
};
public UnitTestBase(String stringXmlPath) {
this.stringXmlPath = stringXmlPath;
};
@Before
public void before() {
if (StringUtils.isEmpty(stringXmlPath)) {
stringXmlPath = “classPath*:spring-*.xml”;
}
try {
context = new ClassPathXmlApplicationContext(stringXmlPath.split("[,\s]+"));
context.start();
} catch (Exception e) {
e.printStackTrace();
}
}
@After
public void after() {
context.destroy();
}
@SuppressWarnings(“unchecked”)
protected T getBean(String beanId) {
return (T) context.getBean(beanId);
}
protected T getBean(Class clazz) {
return context.getBean(clazz);
}
}
注意: 1:引入junit 在Eclipse中点击项目右键->build path ->configure build Path -> libraries->add library->junit->next->finish
2.下载跟你Eclipse版本一样的包 ,放在你创建工程项目lib文件夹下
就可以用了。