作为java web程序员,我们经常要写junit测试,在不启动整个web项目的情况下,测试自己的service实现或者是dao实现,我们来充分利用下junit4的强大功能。
1. 新建一个junit4的测试case,要继承AbstractJUnit4SpringContextTests类,该父类能够调用spring context
2. 该junit测试类的源码
package com.zkyj.core.test.init;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.zkyj.core.dao.StudyRoomGeneralDao;
import com.zkyj.core.entity.vo.studyRoom.StudyVocabularyVo;
@ContextConfiguration(locations = {"classpath*:/META-INF/jdbc-context.xml","classpath*:/META-INF/springMvc3-servlet.xml","classpath*:/META-INF/consumer.xml"})
public class VocMediaToZip extends AbstractJUnit4SpringContextTests {
@Autowired
private StudyRoomGeneralDao studyRoomGeneralDao;
/**
* 执行run as Junit Test,就会执行有@Test注解的方法,相当于普通java类的main方法
* 该实例中可以直接调用spring已经注入的bean即studyRoomGeneralDao
* 2015年6月26日
*/
@Test
public void test() {
try {
ListtaskList = getTaskVocList(139);
System.out.println(taskList == null ? 0 : taskList.size());
} catch (Exception e) {
e.printStackTrace();
}
}
private ListgetTaskVocList(int taskId) throws Exception{
return studyRoomGeneralDao.getEntityList(
StudyVocabularyVo.class,
" SELECT voc.*,img.`imgUrl` FROM `study_scheme_task_voc` AS task_voc "
+ "LEFT JOIN `voc_detail` voc ON task_voc.`vocId` = voc.`id` "
+ "LEFT JOIN `voc_img` img ON voc.`id` = img.`vocabularyId` "
+ "WHERE task_voc.taskId = ?",
new Object[]{taskId});
}
}
3. 源码中有些注释已经写的很清楚,接下来详细介绍下:
@ContextConfiguration(locations = {"classpath*:/META-INF/jdbc-context.xml","classpath*:/META-INF/springMvc3-servlet.xml","classpath*:/META-INF/consumer.xml"})
public class VocMediaToZip extends AbstractJUnit4SpringContextTests {
以上注解,会将spring context的bean全部注册到context中,这样在junit类中就可以随意使用spring 相关的实体bean对象了。当然我们的测试类必须继承AbstractJUnit4SpringContextTests
还有其他疑问请留言。
4. 运行该junit
执行run as Junit Test,就会执行有@Test注解的方法,相当于普通java类的main方法,每个junit测试类至少要有一个@test注解的方法,可以有多个,多个则按顺序执行方法。
@Test
public void test() {
try {
ListtaskList = getTaskVocList(139);
System.out.println(taskList == null ? 0 : taskList.size());
} catch (Exception e) {
e.printStackTrace();
}
}
如图执行该测试类:右键编辑器窗口选择Run As---->JUnit Test
如有任何问题,欢迎留言。
(转载本站原创文章请注明作者与出处Coding云--codingyun.com)





