maven專案的單元測試和遇到的問題
一、程式碼示例
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
希望對大家有所幫助。