maven项目的单元测试和遇到的问题

来源:互联网 发布:java 如何打包jar文件 编辑:程序博客网 时间:2024/06/05 10:38

一、代码示例

1.spring+junit整合写法

这种写法可以直接用注解自动注入service进行测试,较为方便,需要引入spring-test的jar包

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.csdn.net/xukaixun005/article/details/52698852

希望对大家有所帮助。