❶ 如何使用junit測試javaweb工程
一:創建一個測試類,建議將測試類單獨放在一個包中(在 maven 項目里有測試類專門的存放位置),新建一個Junit Test Case類,下一步
測試類的命名建議是你將要測試的類名+Test,然後點 Browse, 你可以選擇要進行測試的類(一般選擇 Service, 因為 Service 關心的是業務需求),用這種方式創建可以自動生成要測試類的測試類,你只需要進行測試代碼的書寫.
@Test
public void testqueryById(){
} @Test
public void testQueryAll(){
} @Test
public void testReceNumber(){
}123456789101112
如果裡面有自動生成的代碼,刪除或注釋即可…
二:配置 spring 和 junit 整合, junit 啟動時載入 springIOC 容器,這里你需要 Spring-test jar包
@RunWith(SpringJUnit4ClassRunner.class) //告訴junitspring配置文件
@ContextConfiguration(locations = {"classpath:spring/spring-.xml"})123
同樣的,在測試類中我們會調用 Service 的邏輯,由於我們使用的是 Spring+SpringMVC+ 持久化框架,所以要注入一個 IService 介面(這里我直接對 DAO 進行測試了)
@Autowired
private SeckillDao seckillDao;12
接下來是測試邏輯,在編寫測試代碼之前建議覆蓋實體中的 toString 方法,不然列印會很麻煩.
@Test public void testqueryById(){ long id = 1000;
Seckill seckill = seckillDao.queryById(id);
System.out.println(seckill.getSeckillName());
System.out.println(seckill);
} //JAVA沒有保存形參的記錄,如果你在 中傳了多個參數,那麼需要聲明它的形參對應的實參,否則 JVM 會顯示找不到參數.聲明方式稍後奉上
@Test public void testQueryAll(){
List<Seckill> seckills = seckillDao.queryAll(0, 100); for(Seckill seckill:seckills){
System.out.println(seckill);
}
}
@Test public void testReceNumber(){
Date killTime = new Date(); //對增加進行測試的時候,只要資料庫增加了一條數據,我們就默認這個方法執行成功了
int updateCount = seckillDao.receNumber(1000L, killTime);
System.out.println("updateCount = "+updateCount);
}
解決JAVA不保存形參的記錄
int receNumber(@Param("seckillId")long seckillId,@Param("killTime")Date killTime);
Seckill queryById(long seckillId); /**
* mysql的分頁查詢
* @param offset 告訴它實際的形參
* @param limit
* @return
*/
List<Seckill> queryAll(@Param("offset")int offset,@Param("limit")int limit);1234567891011
接下來我們根據他返回的結果和我們想要的結果對應就可以了. 測試類不用部署項目, 測試周期非常短, 而且可以進行專項測試. 測試類代碼邏輯十分簡單, 幾乎不會出錯. 如果結果不是預期的, 那麼根據你的需求修改!
當然, 它的局限性也很打. 從單元測試不能看出頁面傳值的錯誤, 許多項目在伺服器中的表現也不能模擬.
那麼我們什麼時候用junit呢?
當你的資料庫操作非常復雜, 你不確定能輸出你想要的值的時候, 相比用 debug 調試, 使用 Junit 是更方便的手段.或者新手出錯概率非常大, 也不用在伺服器中專門測試項目的表現, Junit 是個必備的工具!而且測試類的測試代碼重用性很高.
如果你的數據和預期相悖, 那麼修改業務邏輯; 否則, 查看頁面是否有錯! Junit在一定程度上減輕了我們業務代碼調試的壓力, 讓我們關注於一點解決錯誤.
❷ 在spring和junit整合中出現java.lang.NoClassDefFoundError: javax/servlet/ServletContext錯誤
我印象里好像也出現過,我把我的配置方式給你說一下,你看能不能跑起來。
如果你是springMVC可以採用下面說的,springboot另說,更簡單。
首先這幾個jar得有:junit-4.12.jar、hamcrest-core-1.3.jar和spring-test-4.3.6.RELEASE.jar。
其次你看下我的Test類:
所以我填的是classpath:web/WEB-INF/applicationContext.xml
❸ 怎麼創建junit4 注入spring 配置文件
1 建立一個test的目錄,在此目錄下放置所有的JunitTestCase類和TestCase的配置文件
2 將項目中的Spring配置文件(默認名稱為applicationContext.xml)復制到test目錄下,並重新命名為JunitTestConf.xml。
3 根據Junit測試的需要修改JunitTestConf.xml文件中的內容,如資料庫連接等。
4 新建一個名為SpringConfForTest.java的類,在此類中配置Spring啟動所需的配置文件,並啟動Spring。此類的內容如下:
package test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.;
import com.soma.global.WebContextHolder;
public class SpringConfForTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
//Spring啟動所需要的配置參數文件,其中test/JunitTestConf.xml文件中保存了資料庫連接等參數,可根據具體情況做修改
String[] paths = new String[] {"test/JunitTestConf.xml", "com/soma/conf/applicationContext--hr.xml","com/soma/conf/applicationContext-.xml","com/soma/conf/applicationContext--bug.xml","com/soma/conf/applicationContext--change.xml","com/soma/conf/applicationContext--common.xml","com/soma/conf/applicationContext-service-hr.xml" };
//啟動Spring,得到Spring環境上下文
ApplicationContext ctx = new (paths);
//在此類啟動時,將Spring環境上下文保存到單根類WebContextHolder中,以提供給其它的測試類使用
WebContextHolder.getInstence().setApplicationContext(ctx);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Test
public void test(){
//必須要寫一個test空方法,否則SpringConfForTest類不會啟動
}
}
5 新建TestSuite類,類名為AllTests,類的內容如下所示:
package test;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import test.com.soma.domain.busilogic.hr.HrBusiLogicTest;
import test.com.soma.domain.service.hr.checkOverTimeDateTest;
@RunWith(Suite.class)
@Suite.SuiteClasses({
SpringConfForTest.class,
HrBusiLogicTest.class,
checkOverTimeDateTest.class
})
/**
* 批量執行Junit測試類,把類名寫入到上面的Suite.SuiteClasses({})中,用逗號分隔
*/
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Test for test");
//$JUnit-BEGIN$
//$JUnit-END$
return suite;
}
}
注意:將SpringConfForTest.class放在第一個執行,以啟動Spring配置環境,把自己的TestCase類放到後面,用逗號分開。在測試時,只要執行這個TestSuite類就可以了。
6 寫自己的TestCase類,以CheckOverTimeDateTest.java為例子,文件內容如下:
public class CheckOverTimeDateTest {
private static HrTbovertimeManager hrTbovertimeManager;
private static ExcuteSqlDAO excuteSqlDAO;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
//從Spring上下文中得到hrTbovertimeManager介面類的實例
hrTbovertimeManager=(HrTbovertimeManager)BeanUtil.getBean("hrTbovertimeManager");
excuteSqlDAO = (ExcuteSqlDAO) BeanUtil.getBean("excuteSqlDAO");
}
@Test
public void testGetProjectList()throws Exception {
List<OvertimeDetailValue> overtimeDetailValueList = new ArrayList<OvertimeDetailValue>();
int index = 9;
for(int i = 1 ;i <= index;i++){
OvertimeDetailValue overtimeDetailValue = new OvertimeDetailValue();
overtimeDetailValue.setOtApplyDate("2009-05-0"+i);
overtimeDetailValueList.add(overtimeDetailValue);
}
String resultStr = hrTbovertimeManager.checkOverTimeDate(overtimeDetailValueList);
assertEquals("false", resultStr);
}
/**
* 導入2009-03月份出勤記錄excel文件,返回null表示導入成功,需要先刪除3月份的數據
*/
@Test
public void testSaveExcelDutyInformation() throws Exception{
// 在導入3月份出勤記錄前先刪除3月份的記錄,執行delete from hr_tbtyinformation;
excuteSqlDAO.excuteSql("delete from hr_tbtyinformation where tydate>='2009-02-26' and tydate<='2009-03-25'");
// System.out.println("----------"+System.getProperty("user.dir")+"/src/test/ty200903.xls");
String fileName = System.getProperty("user.dir")
+ "/src/test/ty200903.xls";
assertNull(hrTbtyInformationManager.saveExcelDutyInformation(fileName));
}
}
說明:BeanUtil.getBean("")相當於WebContextHolder.getInstence().getApplicationContext().getBean(""),只是對此方法做了封裝。
7 在Eclipse中,啟動AllTests,選擇「Run As JunitTest」,即可先啟動Spring環境,再依次運行你自己所寫的JunitTestCase,是不是很簡單哪?趕快動手試試吧。
❹ 基於maven的web工程集成spring後在junit測試類中實例化容器後取不到Bean對象
Spring中的幾種容器都支
持使用xml裝配bean,包括:
XmlBeanFactory ,
,
,
XmlWebApplicationContext
使用web.xml中配置的spring啟動方式與junit中裝配的方式不同,與maven無關,你用junit測試XXservice,應該先把bean裝配起來,不知道親懂沒
❺ spring test 怎麼讀取web-inf下的applicationcontext
假設Spring配置文件為applicationContext.xml
一、Spring配置文件在類路徑下面
在Spring的java應用程序中,一般我們的Spring的配置文件都是放在放在類路徑下面(也即編譯後會進入到classes目錄下)。
以下的項目,因為是用maven管理的,所以配置文件都放在「src/main/resources」目錄下
這時候,在代碼中就不可以使用來載入配置文件了,而應使用。
Java代碼
=new("src/main/webapp/WEB-INF/applicationContext.xml");
然後獲取相應的bean。
如果代碼想用Junit測試框架來測試,則Spring提供了對Junit支持,還可以使用註解的方式:
Java代碼
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/applicationContext.xml"})
只需要在相應的Test類前面加上此兩個註解(第二個註解用來指明Spring的配置文件位置),就可以在Junit Test類使用中Spring提供的依賴注入功能。
下面是一個Spring管理下的Junit測試類:
Java代碼
packagecom.sohu.group.service.external;
importjava.util.List;
importorg.junit.Test;
importorg.junit.runner.RunWith;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.test.context.ContextConfiguration;
importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"file:src/main/webapp/WEB-INF/applicationContext.xml"})
{
@Autowired
;
@Test
(){
List<String>list=suFriendService.getUserFollowerList("liug_talk@163.com");
System.out.println("------"+list);
}
}
❻ 如何用Junit4測試Spring框架下配置的類
如何用Junit4測試Spring框架下配置的類
前幾天,我們在做Junit4的單元測試時,遇到了問題,就是Junit無法獲得spring的配置環境,即Junit無法得到Spring創建的類實例。
在查閱了網上的一些資料和同事的幫助下,成功的解決了此問題。步驟如下:
1 建立一個test的目錄,在此目錄下放置所有的JunitTestCase類和TestCase的配置文件
2 將項目中的Spring配置文件(默認名稱為applicationContext.xml)復制到test目錄下,並重新命名為JunitTestConf.xml。
3 根據Junit測試的需要修改JunitTestConf.xml文件中的內容,如資料庫連接等。
4 新建一個名為SpringConfForTest.java的類,在此類中配置Spring啟動所需的配置文件,並啟動Spring。此類的內容如下:
package test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.;
import com.soma.global.WebContextHolder;
public class SpringConfForTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
//Spring啟動所需要的配置參數文件,其中test/JunitTestConf.xml文件中保存了資料庫連接等參數,可根據具體情況做修改
String[] paths = new String[] {"test/JunitTestConf.xml", "com/soma/conf/applicationContext--hr.xml","com/soma/conf/applicationContext-.xml","com/soma/conf/applicationContext--bug.xml","com/soma/conf/applicationContext--change.xml","com/soma/conf/applicationContext--common.xml","com/soma/conf/applicationContext-service-hr.xml" };
//啟動Spring,得到Spring環境上下文
ApplicationContext ctx = new (paths);
//在此類啟動時,將Spring環境上下文保存到單根類WebContextHolder中,以提供給其它的測試類使用
WebContextHolder.getInstence().setApplicationContext(ctx);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Test
public void test(){
//必須要寫一個test空方法,否則SpringConfForTest類不會啟動
}
}
5 新建TestSuite類,類名為AllTests,類的內容如下所示:
package test;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import test.com.soma.domain.busilogic.hr.HrBusiLogicTest;
import test.com.soma.domain.service.hr.checkOverTimeDateTest;
@RunWith(Suite.class)
@Suite.SuiteClasses({
SpringConfForTest.class,
HrBusiLogicTest.class,
checkOverTimeDateTest.class
})
/**
* 批量執行Junit測試類,把類名寫入到上面的Suite.SuiteClasses({})中,用逗號分隔
*/
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Test for test");
//$JUnit-BEGIN$
//$JUnit-END$
return suite;
}
}
注意:將SpringConfForTest.class放在第一個執行,以啟動Spring配置環境,把自己的TestCase類放到後面,用逗號分開。在測試時,只要執行這個TestSuite類就可以了。
6 寫自己的TestCase類,以CheckOverTimeDateTest.java為例子,文件內容如下:
public class CheckOverTimeDateTest {
private static HrTbovertimeManager hrTbovertimeManager;
private static ExcuteSqlDAO excuteSqlDAO;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
//從Spring上下文中得到hrTbovertimeManager介面類的實例
hrTbovertimeManager=(HrTbovertimeManager)BeanUtil.getBean("hrTbovertimeManager");
excuteSqlDAO = (ExcuteSqlDAO) BeanUtil.getBean("excuteSqlDAO");
}
@Test
public void testGetProjectList()throws Exception {
List<OvertimeDetailValue> overtimeDetailValueList = new ArrayList<OvertimeDetailValue>();
int index = 9;
for(int i = 1 ;i <= index;i++){
OvertimeDetailValue overtimeDetailValue = new OvertimeDetailValue();
overtimeDetailValue.setOtApplyDate("2009-05-0"+i);
overtimeDetailValueList.add(overtimeDetailValue);
}
String resultStr = hrTbovertimeManager.checkOverTimeDate(overtimeDetailValueList);
assertEquals("false", resultStr);
}
/**
* 導入2009-03月份出勤記錄excel文件,返回null表示導入成功,需要先刪除3月份的數據
*/
@Test
public void testSaveExcelDutyInformation() throws Exception{
// 在導入3月份出勤記錄前先刪除3月份的記錄,執行delete from hr_tbtyinformation;
excuteSqlDAO.excuteSql("delete from hr_tbtyinformation where tydate>='2009-02-26' and tydate<='2009-03-25'");
// System.out.println("----------"+System.getProperty("user.dir")+"/src/test/ty200903.xls");
String fileName = System.getProperty("user.dir")
+ "/src/test/ty200903.xls";
assertNull(hrTbtyInformationManager.saveExcelDutyInformation(fileName));
}
}
說明:BeanUtil.getBean("")相當於WebContextHolder.getInstence().getApplicationContext().getBean(""),只是對此方法做了封裝。
7 在Eclipse中,啟動AllTests,選擇「Run As JunitTest」,即可先啟動Spring環境,再依次運行你自己所寫的JunitTestCase
❼ junit 測試spring時報錯 no bean named 『bookBO 』的錯
把spring配置文件貼出來看下,可能配置錯了,也有可能是沒起web伺服器,容器里還沒有這個bean
❽ junit測試時,spring怎麼讀放在WEB-INF/上的xml文件
配合spring-text.jar
類上面寫註解
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:config/application-context.xml")
config/application-context.xml是路徑
再寫一個text方法,加個註解@Text