1、在maven中導入
junit-4.12.jar;
spring-test.jar;(版本號要與項目spring版本一致)
hamcrest-core-1.3.jar;(這個包是配合junit使用,不然在導入SpringJUnit4ClassRunner.class時里面繼承的BlockJUnit4ClassRunner無法引用)
2、代碼實例
package cn.ljs.util.InterfaceDemo;
import cn.ljs.entity.PurchaseBidNotice;
import cn.ljs.service.FBYQNoticeService;
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;
import java.util.List;
import java.util.Map;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-tx.xml"})
public class TestDemo {
@Autowired
FBYQNoticeService fbyqNoticeService;
@Test
public void test(){
PurchaseBidNotice fb = new PurchaseBidNotice();
List<Map<String,Object>> list = fbyqNoticeService.findAll(fb);
System.out.println(list);
}
}
在學習用spring注入完成junit單元測試時我遇到了以下幾個錯誤
1、spring-test.jar是項目spring版本不一致;
2、junit-4.12.jar與hamcrest-core-1.3.jar是相輔相成的,想要正常使用就必須兩個都引用,我用idea開發junit要到用4.12版本才能用,4.11都不行;
3、spring-tx.xml、spring-mybatis.xml、spring-mvc.xml用<import/>引入相互之間的調用,不要容易出現xx無法引用;
4、如果在spring配置文件里使用了<mvc:resources/>標簽進行靜態資源的調用,會報錯影響junit運行,建議在做單元時注釋;
5、我用IDEA開發時classpath:spring-*.xml,老是找不到,后面在通過下圖方式解決;
1找到配置文件夾;2點擊;3右邊出現后就可以了;
總結:學習中多次重復反復的重啟測試,運行方法控制台一次又一次報紅,當耐心消耗到沒有的時候,突然可以;所以
如果你已經花費一定的時間去做某件事情還是一次又一次的失敗,你開始懷疑自己開始不自信,請你堅持住,你離成功就差臨門一腳,許多人就是因為這
最后一腳放棄了。
————————只為延續被幫助過的感動。

