(2).mybatis单元测试(junit测试)
⼀、Junit使⽤步骤:
1、创建测试⽬录,(src、测试⽬录是test)
2、在测试⽬录test中创建与src中相同的包名
3、为需要测试的类创建测试类,例如:UsersMapper,测试类是UsersMapperTest
4、为被测试类(UsersMapper)中的需要测试的⽅法在测试类型创建相应的⽅法。⽐如,需要测试findById⽅法,那么则测试类中创建findById⽅法,测试⽅法的要求
a、不能有返回值、不能有参数
b、需要只⽤@Test注解对该⽅法进⾏注解。
5、在测试⽅法中,使⽤断⾔对结果进⾏判断,assert,判断
⼀。单元测试
1. 在项⽬下创建⼀个⽬录test,之后将test右键Mark Directory as(标记⽬录为)->测试源根
2. 在test下创建类,类的包名与被测试类的包名⼀致,在被测试类后⾯加上Test,例如:com.dao.UsersMapper与
com.dao.UsersMapperTest。在测试⽅法前@Test,导⼊junit测试路径,点击确定即可,之后maven后台下载。
3. Mybatis的核⼼对象:SqlSessionFactoryBuilder , SqlSessionFactory , SqlSession。(SqlSessionFactoryBuilder创建⼯⼚,⼀般只⽤⼀
次。SqlSessionFactory是⼯⼚,⼯⼚长期存在。SqlSession例如是⼯⼚造的汽车,有时间期限,即使⽤完⼯⼚依旧存在。) SqlSeessionFactoryBuilder⽤过即丢,可⽤来创建多个SqlSessionFactory实例,并提供多个build⽅法的重载来构建SqlSessionFactory. SqlSession(⼀般瞬时、短链接,也可以长连接,⽤完关闭)
build(InputStream inputStream,String environment,Properties properties)
build(Reader reader,String environment,Properties properties)
build(Configuration config)
配置信息以三种形式提供给 SqlessionFactoryld 的build ⽅法:
InputStream(字节流) Reader (字符流) Configuration (类)
读取XML⽂件构造⽅式:
String CONFIG_FILE = "l";
InputStream resourceAsStream = ResourceAsStream(CONFIG_FILE);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder().build(resourceAsStream);
//⾮静态成员,实例成员,成员变量,通过构造⽅法初始化。静态函数,成员通过静态代码块初始化
4. 实现测试⽅法,在每个测试⽅法之前加@Test,实例化Session(建议通过⼯⼚获取,不建议通过new获取。)写测试⽅法,之后进⾏断
⾔操作Assert。Assert.assertNotNull(user),断⾔成功就是=true,断⾔失败,后⾯的代码不会执⾏了。eg:
1package com.dao;
2
3import com.bean.Users;
4import org.apache.ibatis.io.Resources;
5import org.apache.ibatis.session.SqlSession;
6import org.apache.ibatis.session.SqlSessionFactory;
7import org.apache.ibatis.session.SqlSessionFactoryBuilder;
8import org.junit.Assert;
9import org.junit.Test;
10
11import java.io.IOException;
12import java.io.InputStream;
13
14public class UsersMapperTest {
15static final String CONFIG_FILE = "l";
16static SqlSessionFactory factory;
17//⾮静态成员,实例成员,成员变量,通过构造⽅法初始化。静态函数,成员通过静态代码块初始化
18static{ // 静态代码块
19 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
20try {
21 InputStream resourceAsStream =
22 ResourceAsStream(CONFIG_FILE);
23 factory = builder.build(resourceAsStream);
24 } catch (IOException e) {
25 e.printStackTrace();
26 }
27 }
28 @Test
29public void findById()
30 {
31 SqlSession session = factory.openSession();//⼀般通过⼯⼚获取,不建议通过new获取。
32 Users user = session.selectOne("com.dao.UsersMapper.findById", 1);
33 session.close();
34
35 Assert.assertNotNull(user);
36 Assert.assertEquals("管理员",Nickname());
37 Assert.assertEquals("123",Pwd());
38
39 }
40 }
测试结果:
1 org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
2 18 DEBUG [main] org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
3 19 DEBUG [main] org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
4 19 DEBUG [main] org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
5 19 DEBUG [main] org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
6 142 DEBUG [main] org.ansaction.jdbc.JdbcTransaction - Opening JDBC Connection
7 531 DEBUG [main] org.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 558187323.
8 534 DEBUG [main] com.dao.UsersMapper.findById - ooo Using Connection [sql.cj.jdbc.ConnectionImpl@2145433b]
9 535 DEBUG [main] com.dao.UsersMapper.findById - ==> Preparing: select id,nickname,realname,pwd,phone,email,address,create_time
createTime,type,realid from n_users where id = ?
10 582 DEBUG [main] com.dao.UsersMapper.findById - ==> Parameters: 1(Integer)
11 628 TRACE [main] com.dao.UsersMapper.findById - <== Columns: id, nickname, realname, pwd, phone, email, address, createTime,
type, realidlog4j2 xml配置
12 628 TRACE [main] com.dao.UsersMapper.findById - <== Row: 1, 管理员, null, 123, null, null, null, 2019-10-09 10:06:39, 0, null
13 633 DEBUG [main] org.ansaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection
[sql.cj.jdbc.ConnectionImpl@2145433b]
14 633 DEBUG [main] org.ansaction.jdbc.JdbcTransaction - Closing JDBC Connection
[sql.cj.jdbc.ConnectionImpl@2145433b]
15 633 DEBUG [main] org.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 558187323 to pool.
16
17进程完成,退出码 0
到此单元测试就完成了,接下来是⼀个完整的代码。
5. 单元测试总结代码:
1package com.dao;
2
3import com.bean.Users;
4import org.apache.ibatis.io.Resources;
5import org.apache.ibatis.session.SqlSession;
6import org.apache.ibatis.session.SqlSessionFactory;
7import org.apache.ibatis.session.SqlSessionFactoryBuilder;
8import org.junit.Assert;
9import org.junit.Test;
10
11import java.io.IOException;
12import java.io.InputStream;
ParseException;
SimpleDateFormat;
15import java.util.Calendar;
16import java.util.List;
17import java.util.Date;
18public class UsersMapperTest {
19static final String CONFIG_FILE = "l";
20static SqlSessionFactory factory;
21static{ // 静态代码块
22 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
23try {
24 InputStream resourceAsStream =
25 ResourceAsStream(CONFIG_FILE);
26 factory = builder.build(resourceAsStream);
27 } catch (IOException e) {
28 e.printStackTrace();
29 }
30 }
31 @Test // Alt+enter
32public void findById(){
33 SqlSession session = factory.openSession();
34 Users user = session.selectOne("com.dao.UsersMapper.findById", 1);
35// ⼿⼯的、⾁眼的、主观的、⼈品的⽅式判断程序的成熟度
36 System.out.println();// TRACE/DEBUG/INFO/ERROR
37// ⾃动的、断⾔的、客观的、量化的⽅式判断程序的成熟度
38 Assert.assertNotNull(user);
39 Assert.assertEquals("管理员",Nickname());
40 Assert.assertEquals("123",Pwd());
41 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
42 String date = df.CreateTime());
43 Assert.assertEquals("2019-10-09 10:06:39",date);
44 }
45 @Test
46public void findAll(){
47 SqlSession session = factory.openSession();
48 List<Users> list = session.selectList("com.dao.UsersMapper.findAll");
49 Assert.assertNotNull(list);
50 Assert.assertEquals(3,list.size());<!--!验证表⾥记录条数-->
52 Assert.assertEquals("管理员",(0).getNickname());
53 }
54 @Test
55public void add(){
56 Users user = new Users();
57 user.setNickname("zhaoliu");
58 user.setRealname("赵六");
59 user.setPhone("11111");
60 user.setEmail("11111@111");
61 user.setAddress("111");
62 user.setPwd("123");
63 user.setCreateTime(new java.util.Date());
64 SqlSession session = factory.openSession();
65 session.insert("com.dao.UsersMapper.add",user);
66 sessionmit(); <!--!提交事务-->
67 Users userDb = session.selectOne("com.dao.UsersMapper.findById",6); <!--!id以实际为准-->
68 Assert.assertNotNull(userDb);
69 Assert.assertEquals("赵六",Realname());
70 session.close();
71 }
72 @Test
73public void update() throws ParseException {
74 SqlSession session = factory.openSession();
75 Users dbUser = session.selectOne("com.dao.UsersMapper.findById",6);
76 Assert.assertNotNull(dbUser);
77 dbUser.setNickname("zhaoliu");
78// 2020-03-03 14:13:23 => 2019-10-09 10:11:42 : 2种
79/*Calendar cl = Instance(); // 当前时间
80 cl.set(Calendar.YEAR,2019);
81 cl.set(Calendar.MONTH,9); // 0-11
82 cl.set(Calendar.DAY_OF_MONTH,9); // 1-31
83 cl.set(Calendar.HOUR_OF_DAY,10); // 0-23
84 cl.set(Calendar.MINUTE,11); // 1-60
85 cl.set(Calendar.SECOND,42); // 1-60
86 cl.set(Calendar.MILLISECOND,0); Date Time();*/
87 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
88 Date date = df.parse("2020-10-09 10:11:43"); //常⽤于判断从⽹络接受的时间
89 dbUser.setCreateTime(date);
90 session.update("com.dao.UsersMapper.update",dbUser);
91 sessionmit();
92 Users user = session.selectOne("com.dao.UsersMapper.findById",6);
93 Assert.assertNotNull(user);
94 Assert.assertEquals("zhaoliu",Nickname());
95 Assert.assertEquals(CreateTime());
96 }
97 @Test
98public void delete(){
99// hibernate,mybatis
100// 主从表/⽗⼦表的概念?主表-主键所在的表,从表-外键所在的表
101// 1、添加数据:先为主表添加数据,后为从表添加数据
102// 2、删除数据:先删除从表数据,然后删除主表数据
103// n_users (主表) 的从表:n_news,n_replys,n_short_replys,n_access_logs
104// a主->b从->c从->d从,不创建外键(外键关系是存在的)
105 SqlSession session = factory.openSession();
106 session.delete("com.dao.AccessLogsMapper.deleteByUsersId",6);
107 session.delete("com.dao.ShortReplysMapper.deleteByUsersId",6);
108 session.delete("com.dao.ReplysMapper.deleteByUsersId",6);
109 session.delete("com.dao.NewsMapper.deleteByUsersId",6);
110 session.delete("com.dao.UsersMapper.delete",6);
111 sessionmit();
112 Users user = session.selectOne("com.dao.UsersMapper.findById",6);
113 Assert.assertNull(user);
114 }
115 }
在执⾏删除操作时,记得删除外键⾥的记录,后删除主键内的记录。 // 主从表/⽗⼦表的概念?主表-主键所在的表,从表-外键所在的表
101 // 1、添加数据:先为主表添加数据,后为从表添加数据
102 // 2、删除数据:先删除从表数据,然后删除主表数据
103 // n_users (主表) 的从表:n_news,n_replys,n_short_replys,n_access_logs
104 // a主->b从->c从->d从,不创建外键(外键关系是存在的)
6. 之后依次把实体类,实现Mapper,并在主配置⽂件中配置,Mapper。
7. 学会审视⾃⼰的代码,=》审查(语法错误,逻辑错误)、优化、重构。
8. 增加⽅法:@Before:是表⽰在每⼀个测试⽅法执⾏前,都会调⽤该⽅法。
9. 增加⽅法:@BeforeClass:是表⽰在多个单元测试⽅法中,⽆论有多少个测试⽅法,都只执⾏⼀次。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论