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右边出现后就可以了;
总结:学习中多次重复反复的重启测试,运行方法控制台一次又一次报红,当耐心消耗到没有的时候,突然可以;所以 如果你已经花费一定的时间去做某件事情还是一次又一次的失败,你开始怀疑自己开始不自信,请你坚持住,你离成功就差临门一脚,许多人就是因为这 最后一脚放弃了。 ————————只为延续被帮助过的感动。