是指对软件中的最小可测试单元进行检查和验证的过程。
准备工作:确认项目中已经内置了测试框架。(高版本的spring boot已经内置)
1.先生成单元测试的类
2. 配置单元测试的类添加@SpringBootTest注解,添加单元测试的业务代码
@SpringBootTest//表示当前单元测试运行在spring boot 环境中
class UserMapperTest {
@Autowired //科学版的idea此行代码会报错
private UserMapper userMapper;
@Test
void getUserById() {
UserInfo userInfo= userMapper.getUserById(1);
System.out.println(userInfo);
}
}
@SpringBootTest//表示当前单元测试运行在spring boot 环境中
class UserMapperTest {
@Autowired //科学版的idea此行代码会报错
private UserMapper userMapper;
@Test
void getUserById() {
UserInfo userInfo= userMapper.getUserById(1);
//System.out.println(userInfo);
Assertions.assertNotNull(userInfo);
}
}
@SpringBootTest//表示当前单元测试运行在spring boot 环境中
class UserMapperTest {
@Autowired //科学版的idea此行代码会报错
private UserMapper userMapper;
@Test
void getUserById() {
UserInfo userInfo= userMapper.getUserById(1);
//System.out.println(userInfo);
Assertions.assertNull(userInfo);
}
}
//修改方法【根据id修改名称】
public int update(@Param("id") Integer id,@Param("username") String username);
<update id="update">
update userinfo set username=#{username} where id=#{id}
</update>
测试:
@Test
@Transactional //在单元测试中添加此注解,表示在方法执行完之后回滚事务
void update() {
int result=userMapper.update(2,"zhangsan");
Assertions.assertEquals(1,result);
}
public int del (@Param("id") Integer id);
<delete id="del">
delete from userinfo where id=#{id}
</delete>
测试:
@Test
@Transactional
void del() {
int result=userMapper.del(2);
System.out.println("受影响的行数"+result);
Assertions.assertEquals(1,result);
}
//添加用户,返回受影响行数
public int add(UserInfo userInfo);
2.在xml中添加标签和添加的SQL编写
<insert id="add">
insert into userinfo (username,password,photo) values(#{username},#{password},#{photo});
</insert>
@Test
void add() {
UserInfo userInfo=new UserInfo();
userInfo.setUsername("王五");
userInfo.setPassword("123");
userInfo.setPhoto("default.png");
int result=userMapper.add(userInfo);
System.out.println("添加的结果:"+result);
Assertions.assertEquals(1,result);
}
//添加用户,返回受影响的行数和自增的id
public int addGetId(UserInfo userInfo);
<insert id="addGetId" useGeneratedKeys="true" keyProperty="id">
insert into userinfo (username,password,photo) values(#{username},#{password},#{photo});
</insert>
测试:
@Test
@Transactional
void addGetId() {
UserInfo userInfo=new UserInfo();
userInfo.setUsername("六六六");
userInfo.setPassword("123");
userInfo.setPhoto("default.png");
System.out.println("添加之前 user id: "+userInfo.getId());
int result=userMapper.addGetId(userInfo);
System.out.println("受影响的行数:"+result);
System.out.println("添加之后 user id:"+userInfo.getId());
Assertions.assertEquals(1,result);
}