验证Dao
1、测试流程:
①定义一个实体类和数据库数据相对应
②编写dao对应的接口,不用编写其实现类,因为我们用的是mapper.xml的方式实现的
③在xml中编写dao接口对应的sql实现方式
④编写Junit测试基础类,其他测试类继承该类,在其他测试类中就可以不用每次填写相同的配置
@RunWith(SpringJUnit4ClassRunner.class)设定运行的类
@ContextConfiguration({“classpath:spring/spring-dao.xml”})告诉Junit配置文件在哪
⑤运行Junit,看是否显示结果正确
2、相关类如下:
package com.imooc.o2o.entity;
import java.util.Date;
public class Area {
private Long areaId;
private String areaName;
private Integer priority;
private Date createTime;
private Date lastEditTime;
public Long getAreaId() {
return areaId;
}
public void setAreaId(Long areaId) {
this.areaId = areaId;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getLastEditTime() {
return lastEditTime;
}
public void setLastEditTime(Date lastEditTime) {
this.lastEditTime = lastEditTime;
}
}
package com.imooc.o2o.dao;
import java.util.List;
import com.imooc.o2o.entity.Area;
public interface AreaDao {
/**
* 列出地域列表
*
* @param areaCondition
* @return
*/
List<Area> queryArea();
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.imooc.o2o.dao.AreaDao">
<select id="queryArea" resultType="com.imooc.o2o.entity.Area">
select area_id,area_name,priority,create_time,last_edit_time
from tb_area
order by priority desc
</select>
</mapper>
package com.imooc.o2o;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-dao.xml"})
public class BaseTest {
}
package com.imooc.o2o.dao;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.imooc.o2o.BaseTest;
import com.imooc.o2o.entity.Area;
public class AreaDaoTest extends BaseTest{
@Autowired
private AreaDao areaDao;
@Test
public void testQueryArea() {
List<Area> areaList = areaDao.queryArea();
assertEquals(2, areaList.size());
}
}
3、测试时实现同一类中的方法按照一定规则先后执行(数据回环)
在Junit测试方法中为实现测试的回环,即增->改->删,保证数据原始性
可以在测试类上增加注解@FixMethodOrder(MethodSorters.NAME_ASCENDING),添加了这个主键之后会按照类名先后顺序执行 即 A B C