发表于: 2025-03-23 19:28:40
0 11
今天完成的事情:
对Mybatis连接数据库的增删改查进行junit单元测试
package com.example.dao.impl;
import com.example.mapper.UserMapper;
import com.example.model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class UserDaoImplTest {
static SqlSessionFactory sqlSessionFactory;
static {
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
void addUser() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setName("Tom");
int i = userMapper.addUser(user);
sqlSession.commit();
sqlSession.close();
assertEquals(1, i);
}
@Test
void updateUser() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setId(1);
user.setName("Jerry");
userMapper.updateUser(user);
sqlSession.commit();
sqlSession.close();
}
@Test
void deleteUser() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int i = userMapper.deleteUser(58);
sqlSession.commit();
sqlSession.close();
assertEquals(1, i);
}
@Test
void queryAllUsers() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> users = userMapper.queryAllUsers();
// 确保查询返回的结果非空
assertTrue(users != null && users.size() > 0, "查询结果为空");
for (User user : users) {
System.out.println("用户ID: " + user.getId());
System.out.println("用户名: " + user.getName());
System.out.println("用户QQ: " + user.getQQ());
System.out.println();
}
}
@Test
void getUserById() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(3);
System.out.println("用户ID: " + user.getId());
System.out.println("用户名: " + user.getName());
System.out.println("用户QQ: " + user.getQQ());
sqlSession.close();
}
@Test
void commitAndClose() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setName("Jerry");
userMapper.addUser(user);
sqlSession.commit();
sqlSession.close();
}
}
明天计划的事:
- 学习一些mabits的基础知识。
遇到的问题:
对Mybatis连接数据库的格式不对,在学长帮助下进行了多次修改。
收获:
- 对Mybatis连接数据库的增删改查进行单元测试。
评论