Spring单元测试

spring单元测试用于测试Mapper/Dao层的工作,推荐SPring项目使用Spring的单元测试,可以自定义注入我们需要的组件,步骤为:
1.导入SpringTest模块;
2.@ContextConfiguration指定Spring配置文件的位置;
3.直接@Autowired要使用的组件即可。
例子:
package com.xc.ssm.test;

import java.util.UUID;

import org.apache.ibatis.session.SqlSession;
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.xc.ssm.bean.Department;
import com.xc.ssm.bean.Employee;
import com.xc.ssm.mapper.DepartmentMapper;
import com.xc.ssm.mapper.EmployeeMapper;

/**

  • 测试mapper/dao层的工作

  • 推荐Spring的项目就可以使用Spring的单元测试,可以自定注入我们需要的组件:

  • 1.导入SpringTest模块;

  • 2.@ContextConfiguration指定的SPring配置文件的位置;

  • 3.直接Autowired要使用的组件即可。
    */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations={“classpath:applicationContext.xml”})
    public class MapperTest {

    /**

    • @Autowired注解:自动装配mapper对象
      */
      @Autowired
      DepartmentMapper departmentMapper;

    @Autowired
    EmployeeMapper employeeMapper;

    @Autowired
    SqlSession sqlSession;

    @Test
    public void testCRUD() {
    //创建SpringIOC容器
    /* ApplicationContext ctx = new ClassPathXmlApplicationContext(“applicationContext.xml”);
    //从容器中获取Mapper
    DepartmentMapper bean = ctx.getBean(DepartmentMapper.class);*/
    // System.out.println(departmentMapper);
    // System.out.println(bean);

     //插入部门数据——这两句是等价的,即bean和departmentMapper两个对象具有相同的作用
     //bean.insertSelective(new Department(null,"python"));
     departmentMapper.insertSelective(new Department(null,"switch"));
     
     //生成员工数据
    

// employeeMapper.insertSelective(new Employee(null,“kleine”,“M”,"kleine0426@163.com",4));
// System.out.println(“添加员工成功”);

	//批量插入多个员工,使用可以执行批量操作的SqlSession
	/*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,"M",uid+"@163.com",2));
	}
	System.out.println("批量操作完成");*/
	
}

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值