Junit与Spring整合配置

       Junit是在开发中经常用来调试代码的工具,目前在比较流程的SSM框架中,如何把Junit与Spring进行整合,测试对就的业务逻辑以及DAO层的数据提取的问题,关注点是Junit启动时加载SpringIOC容器以及把Spring相关的配置文件引入,具体有两步:

第一步:建立一个测试基类

测试基类的作用是利用那个启动类引入Spring的相关配置文件,代码如图:

package com.imooc.myo2o;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * 配置spring和junit整合,junit启动时加载springIOC容器 spring-test,junit
 */
@RunWith(SpringJUnit4ClassRunner.class)
// 告诉junit spring配置文件
@ContextConfiguration({ "classpath:spring/spring-redis.xml","classpath:spring/spring-dao.xml",
		"classpath:spring/spring-service.xml" })
public class BaseTest {

}

第二步:建立测试类

   所有的测试类都要继承基类,如下代码片段:

package com.imooc.myo2o.dao;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;

import com.imooc.myo2o.BaseTest;
import com.imooc.myo2o.entity.Area;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class AreaDaoTest extends BaseTest {
	@Autowired
	private AreaDao areaDao;

	@Test
	public void testBQueryArea() throws Exception {
		List<Area> areaList = areaDao.queryArea();
		assertEquals(3, areaList.size());
	}

}

说明:

1、测试类中要此处你需要测试的类,例如:DAO,并加注解@Autowired

2、对于测试的方法要加上@Test注解

猜你喜欢

转载自blog.csdn.net/gyshun/article/details/81323546