7.搭建Spring单元测试环境

来源:互联网 发布:天刀淘宝代购怎么赚钱 编辑:程序博客网 时间:2024/05/21 23:32

用逆向工程生成了SQL相关的代码后,先用Spring单元测试一下,看能否走通。

1.在pom中导入Spring TestContext Framework

<!-- https://mvnrepository.com/artifact/org.springframework/spring-test --><dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-test</artifactId>    <version>4.3.7.RELEASE</version>    <scope>test</scope></dependency>

2.指定Spring配置文件的加载位置

@ContextConfiguration(locations = { "classpath:applicationContext.xml" })

3.autowire需要使用的组件

    @Autowired    DepartmentMapper departmentMapper;    @Autowired    EmployeeMapper employeeMapper;    @Autowired    SqlSession sqlSession;

4.完整代码

package com.lee.crud.test;import java.util.UUID;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionManager;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.lee.crud.beans.Department;import com.lee.crud.beans.Employee;import com.lee.crud.dao.DepartmentMapper;import com.lee.crud.dao.EmployeeMapper;/* * 1.导入Spring Test 的jar * 2.@ContextConfiguration用来指定Spring配置文件加载位置 *      @RunWith是Junit测试用的 * 3.直接autowired要使用的组件即可 * */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "classpath:applicationContext.xml" })public class MapperTest {    @Autowired    DepartmentMapper departmentMapper;    @Autowired    EmployeeMapper employeeMapper;    @Autowired    SqlSession sqlSession;    @Test    public void testCRUD(){        System.out.println(departmentMapper);        // 测试插入一个部门        // departmentMapper.insertSelective(new Department(null,"人力资源部"));        // 测试插入一为员工        // employeeMapper.insertSelective(new Employee(7, "mary", "女",        // "mary@qq.com",2));        // System.out.println("插入成功");        //      测试批量插入员工        //      EmployeeMapper mapper =sqlSession.getMapper(EmployeeMapper.class);        //      for(int i=0;i<1000;i++){        //          String uid=UUID.randomUUID().toString().substring(0, 5)+i;        //          mapper.insertSelective(new Employee(null, uid, "男", uid+"@163.com", 1));        //      }        //      System.out.println("批量插入成功!");        //      测试删除数据        //      employeeMapper.deleteByPrimaryKey(1011);        //      System.out.println("删除成功!");        //测试修改数据            employeeMapper.updateByPrimaryKey(new Employee(1012, "sunny", "女", "sunny@163.com", 2));            System.out.println("修改成功");    }}
原创粉丝点击