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();
}