Spring与junit结合测试
假设Spring配置文件为applicationContext.xml
一、Spring配置文件在类路径下面
在Spring的java应用程序中,一般我们的Spring的配置文件都是放在放在类路径下面(也即编译后会进入到classes目录下)。
以下是我的项目,因为是用maven管理的,所以配置文件都放在“src/main/resources”目录下
这时候,在代码中可以通过
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:applicationContext.xml"}) ApplicationContext applicationContext = new FileSystemXmlApplicationContext("src/main/webapp/WEB-INF/applicationContext.xml"); @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/applicationContext.xml"}) package com.sohu.group.service.external; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"file:src/main/webapp/WEB-INF/applicationContext.xml"}) public class SuFriendServiceImplOverRMITest { @Autowired private SuFriendService suFriendService; @Test public void getUserFollowerListTest(){ List<String> list = suFriendService.getUserFollowerList("liug_talk@163.com"); System.out.println("------"+list); } }