目录

单元测试

优势

单元测试的使用

具体步骤

实现不污染数据库 


阅读下面文章之前 建议点击下方链接了解 MyBatis创建使用

MyBatis 的配置与使用



优势


具体步骤

import com.example.demo.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
class UserMapperTest {

//    正因为该测试单元运行在 Spring Boot 下
//    所以我们可以使用依赖注入 userMapper Bean 对象
    @Autowired
    private UserMapper userMapper;

    @Test
    void getUserById() {
        User user = userMapper.getUserById(1);
        System.out.println(user);
    }
}


实例理解


 初始化 UserMapper 接口

import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

//添加 @Mapper 注解 代表该接口会伴随这 项目启动注入到容器中
@Mapper
public interface UserMapper {
    
//    根据 id 修改用户密码
    Integer update(@Param("user_id") Integer id,
                   @Param("new_password") String newPassword);
}

初始化 UserMapper XML 文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybati
s.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">

    <update id="update">
        update user set password = #{new_password} where id = #{user_id};
    </update>

</mapper>

创建 update 的测试方法

@Test
@Transactional
void update() {
    int result = userMapper.update(1,"1234");
    System.out.println("update 方法 :" + (result == 1 ? "成功" : "失败"));
}

执行测试方法


对 JUnit5 感兴趣的 可以点击下方链接详细了解

关于 JUnit5 详解

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注