一、代码示例
1.spring+junit整合写法
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:config/springmvc-servlet.xml"})
public class TestCps{
@Test
public void testPlatCpsUserServiceTest(){
System.out.println("success");
}
}
2.ClassPathXmlApplicationContext加载spring的配置文件获取bean,相对来讲麻烦一点
import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;
import junit.framework.TestCase;
public class BlacklistServiceTest extends TestCase{
private ApplicationContext ctx;
private ActivitylistService activitylistService;
@org.junit.Before
protected void setUp() throws Exception {
ctx = new ClassPathXmlApplicationContext("config/springmvc-servlet.xml");
activitylistService=(ActivitylistService) ctx.getBean("activitylistService");
}
public void testCount(){
System.out.println("0");
}
}
二、问题解决
上面方法运行的时候报错如下:Caused by: java.io.FileNotFoundException: class path resource [config/springmvc-servlet.xml] cannot be opened because it does not exist
其实之前这个问题我是遇到过并解决了的,但是再次遇到一时不知道怎么解决,所以还是写下了以防万一吧-_-
首先肯定是你classpath下面指定的路径没有这个文件,然后我果断点开src/main/resources, 有这个文件啊 搞什么?!
之后我找到target内编译过的测试类文件,发现是在test-classes下面,然而这里是没有spring的配置文件的,真是年轻
其实是这样的,maven对于main和test的代码编译之后是分目录存放的,这样可以在发布时只发布main中的java和resources
当然它们的resources就肯定都是要单独配置了,它们的classpath也是不一样的
我在src/test/resources下加上去配置文件,OK
下面附上一篇关于classpath的文章http://blog.youkuaiyun.com/xukaixun005/article/details/52698852
希望对大家有所帮助。
本文介绍了在maven项目中进行单元测试时,如何整合spring+junit,以及使用ClassPathXmlApplicationContext加载配置文件获取bean。在解决问题过程中,强调了maven对main和test代码编译后的存放目录不同,导致classpath资源配置需要注意src/test/resources目录。通过调整配置,成功解决了找不到配置文件的问题,并分享了一篇关于classpath的参考文章。
1375

被折叠的 条评论
为什么被折叠?



