JavaEE_Junit_Junit对Spring注入的Service层的测试

今天博主遇到一个问题,在Serivce层利用POI导出Excel表格,博主想对这个方法进行测试,

但由于mapper 是注入的, 直接用 main 方法并不成功,报错和出现的问题如下图:


 JavaEE_Junit_Junit对Spring注入的Service层的测试_第1张图片

JavaEE_Junit_Junit对Spring注入的Service层的测试_第2张图片


主要原因:Mapper是调用时候注入的,所以此时Mapper为null



这时候我们可以使用junit 对service进行测试即可解决问题:

博主假设大家已经导入了Junit 包



在文件上单击右键,创建一个单元测试文件,如下图的步骤

JavaEE_Junit_Junit对Spring注入的Service层的测试_第3张图片

选择Junit测试

JavaEE_Junit_Junit对Spring注入的Service层的测试_第4张图片

单击下一步,这时候就可以选择测试哪些方法了

JavaEE_Junit_Junit对Spring注入的Service层的测试_第5张图片



编写测试代码:


重要的步奏,在setUp中读取Spring配置文件,博主用的是Spring+SpringMvc+Mybatis进行开发,Service, Mapper(DAO)等交由Spring管理


JavaEE_Junit_Junit对Spring注入的Service层的测试_第6张图片


JavaEE_Junit_Junit对Spring注入的Service层的测试_第7张图片

配置文件中扫描service

JavaEE_Junit_Junit对Spring注入的Service层的测试_第8张图片


测试代码:

package cn._2vin.yannan.test;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import cn._2vin.yannan.bean.MobileDepartmentTotal;
import cn._2vin.yannan.service.MobileDepartmentTotalService;

public class MobileDepartmentTotalServiceTest {

	private ApplicationContext applicationContext;
	
	@Before
	public void setUp() throws Exception {
		applicationContext = new FileSystemXmlApplicationContext("classpath:spring/applicationContext.xml");
	}

	@Test
	public void testDeleteByPrimaryKey() {
		fail("Not yet implemented");
	}

	@Test
	public void testSelectBySelective() {
		MobileDepartmentTotalService mobileDepartmentTotalService = (MobileDepartmentTotalService)applicationContext.getBean("mobileDepartmentTotalService");
		//MobileDepartmentTotal mobileDepartmentTotal = new MobileDepartmentTotal();
		List list = mobileDepartmentTotalService.selectBySelective(null);
		System.out.println(list.size());
	}

	@Test
	public void testSelectBySelectiveNoPage() {
		fail("Not yet implemented");
	}

	@Test
	public void testSelectBySelectiveCount() {
		fail("Not yet implemented");
	}

	@Test
	public void testExportExcel() {
		MobileDepartmentTotalService mobileDepartmentTotalService = (MobileDepartmentTotalService)applicationContext.getBean("mobileDepartmentTotalService");
		mobileDepartmentTotalService.exportExcel(null);
	}


}


最后只要在想测试的方法,上右击run as junit 即可,

对类测试,则在文件上右击以run as junit




你可能感兴趣的:(JavaEE)