1.添加依赖
<dependency> <groupId>junit</groupId> <!--junit单元测试--> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency>
2.基本使用
import org.junit.After; import org.junit.Before; import org.junit.Test; private InputStream in; private SqlSession sqlSession; private IUserDao userDao; @Before//用于在测试方法执行之前执行 public void init() throws Exception { //1.读取配置文件,生成字节输入流 in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.获取SqlSessionFactory SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); //3.获取SqlSession对象 sqlSession = factory.openSession(); //4.获取dao的代理对象 userDao = sqlSession.getMapper(IUserDao.class); } @Test // 测试执行的方法 public void testFindAll(){ //5.执行查询所有方法 List<User> users = userDao.findAll(); for(User user : users){ System.out.println(user); } } @After//用于在测试方法执行之后执行 public void destroy() throws Exception { //提交事务 sqlSession.commit(); //6.释放资源 sqlSession.close(); in.close(); }