spring注解开发(Spring整合JUnit+MyBatis)(7)

ops/2025/3/4 0:06:38/

目录

一、项目环境初始化。

(1)数据库与数据表。

(2)pom文件中的核心依赖坐标。

(3)实体类。

(4)service层。

(5)dao层。(Mapper代理模式)

(6)Jdbc配置类。

(7)MyBatis配置类。

(8)Spring配置类。

(9)测试类。(App02)

二、Spring整合JUnit+MyBatis。(实操)

(1)导入JUnit核心依赖坐标。

(2)导入Spring整合JUnit核心依赖坐标。

(3)test测试目录下新建测试类。(测试业务层接口)

(4)测试类上使用注解@RunWith("...")。

(5)测试类上使用注解@ContextConfiguration(classes=...)。

(6)使用注解@Autowired自动注入所需对象。

<1>测试方法1:根据id查询用户。(注解@Test)

<2>测试方法2:查询所有用户。(注解@Test)

<3>最终完善后的测试类代码(AccountServiceTest)。

<4>单元测试方法1、2的运行结果。


  • 本篇博客的内容:基于spring的环境将测试完成。
  • JUnit是一个开源的 Java 单元测试框架。它主要用于编写和运行可重复的自动化测试,帮助开发者验证代码的正确性。是后期开发非常值得学习和使用的一个技术。

一、项目环境初始化。

  • 本篇博客项目的基础环境是博主之前学习Spring整合MyBatis的项目上继续完成Spring整合MyBatis整合JUnit。(纯注解开发!)
  • 博客链接:spring注解开发(Spring整合MyBatis——Mapper代理开发模式、(Spring、MyBatis、Jdbc)配置类)(6)-CSDN博客

(1)数据库与数据表。


(2)pom文件中的核心依赖坐标。
<dependencies><!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --><!--mybatis依赖--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.6</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.18</version></dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><!--mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.28</version></dependency><!--Lombok依赖坐标--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.30</version><scope>provided</scope></dependency><!--阿里数据库连接池druid--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.8</version></dependency><!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.3.18</version></dependency><!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.1</version></dependency></dependencies>

(3)实体类。
java">package com.hyl.domain;import lombok.Data;@Data
public class Account {private Integer id;private String name;private Double money;
}

(4)service层。
  • AccountService接口。
java">package com.hyl.service;import com.hyl.domain.Account;import java.util.List;public interface AccountService {/*** 新增* @param account*/void save(Account account);/*** 更新* @param account*/void update(Account account);/*** 删除* @param id*/void delete(Integer id);/*** 根据id查询* @param id* @return*/Account selectById(Integer id);/*** 查询所有* @return*/List<Account> selectAll();
}
  • AccountServiceImpl实现类。
java">package com.hyl.service.impl;import com.hyl.dao.AccountDao;
import com.hyl.domain.Account;
import com.hyl.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountDao accountDao;@Overridepublic void save(Account account) {accountDao.save(account);}@Overridepublic void update(Account account) {accountDao.update(account);}@Overridepublic void delete(Integer id) {accountDao.delete(id);}@Overridepublic Account selectById(Integer id) {return accountDao.selectById(id);}@Overridepublic List<Account> selectAll() {return accountDao.selectAll();}
}

(5)dao层。(Mapper代理模式)
  • AccountDao接口。
java">package com.hyl.dao;import com.hyl.domain.Account;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;import java.util.List;/*** 数据层的操作接口*/
@Repository
public interface AccountDao {/*** 新增*/@Insert("insert into tb_account (name,money) values (#{name},#{money})")void save(Account account);/*** 根据id删除*/@Delete("delete from tb_account where id = #{id}")void delete(Integer id);/*** 更新* @param account*/@Update("update tb_account set name = #{name} , money = #{money} where id = #{id}")void update(Account account);/*** 查询所有* @return*/@Select("select * from tb_account ")List<Account> selectAll();/*** 根据id查询* @param id* @return*/@Select("select * from tb_account where id = #{id}")Account selectById(Integer id);
}

(6)Jdbc配置类。
  • jdbc.properties文件。
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/hyl
jdbc.username=root
jdbc.password=root123
java">package com.hyl.config;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class JdbcConfig {@Value("${jdbc.driver}")private String driver;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String userName;@Value("${jdbc.password}")private String password;/*** 1、定义方法,返回需要管理的bean(这里使用阿里提供的第三方数据源druid)* 2、使用注解@Bean 将方法的返回值声明为一个Spring管理的Bean。* 这意味着Spring会调用这个方法,并将方法的返回值(bean)存储到Spring容器中,供其他组件使用。*/@Beanpublic DataSource dataSource(){DruidDataSource druidDataSource = new DruidDataSource();druidDataSource.setDriverClassName(driver);druidDataSource.setUrl(url);druidDataSource.setUsername(userName);druidDataSource.setPassword(password);return druidDataSource;}
}

(7)MyBatis配置类。
java">package com.hyl.config;import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class MyBatisConfig {@Beanpublic SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();//代替Mybatis核心配置文件标签<typeAliases>ssfb.setTypeAliasesPackage("com.hyl.domain");//因为Jdbc配置类的方法使用了@Bean注解生产DataSource对象的方法。// 则可以使用形参注入DataSource。再通过方法设置使DataSourcessfb.setDataSource(dataSource);//jdbc事务管理默认有spring-jdbc依赖处理return ssfb;}//单独方法代替Mybatis核心配置文件标签<Mappers>//使用spring整合mybatis提供的类MapperScannerConfigurer完成映射文件的扫描@Beanpublic MapperScannerConfigurer mapperScannerConfigurer() {MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();//设置映射在哪些包下mapperScannerConfigurer.setBasePackage("com.hyl.dao");return mapperScannerConfigurer;}
}

(8)Spring配置类。
java">package com.hyl.config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;@Configuration
@ComponentScan("com.hyl")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MyBatisConfig.class})
public class SpringConfig {}

(9)测试类。(App02)
  • 这个测试类是完成Spring整合MyBatis的测试。
java">package com.hyl;import com.hyl.config.SpringConfig;
import com.hyl.domain.Account;
import com.hyl.service.AccountService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App02 {public static void main(String[] args) {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);AccountService accountService = applicationContext.getBean(AccountService.class);Account account = accountService.selectById(2);System.out.println(account);applicationContext.close();}
}
  • Spring整合MyBatis的程序运行测试结果。

二、Spring整合JUnit+MyBatis。(实操)

(1)导入JUnit核心依赖坐标。
  • Maven中央仓库。https://mvnrepository.com/search?q=JUnit


  • 依赖坐标。
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope>
</dependency>

(2)导入Spring整合JUnit核心依赖坐标。
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.3.18</version><scope>test</scope>
</dependency>

(3)test测试目录下新建测试类。(测试业务层接口)
  • 这里以测试业务层接口为案例学习。通常数据层接口很少测试。


(4)测试类上使用注解@RunWith("...")。
  • 这个注解的核心作用:设置类运行器。该注解用来向程序说明这个测试类是使用Spring整合JUnit方式运行程序。
  • 这是Spring整合JUnit的专用类运行器。
java">package com.hyl;import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/*** 测试业务层接口方法*/
@RunWith(SpringJUnit4ClassRunner.class)
public class AccountServiceTest {
}

(5)测试类上使用注解@ContextConfiguration(classes=...)。
  • 该注解用来向程序说明这个测试类的Spring环境。
  • 简单来说:指明程序中的Spring配置类是哪个。
java">package com.hyl;import com.hyl.config.SpringConfig;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/*** 测试业务层接口方法*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {
}

(6)使用注解@Autowired自动注入所需对象。
<1>测试方法1:根据id查询用户。(注解@Test)
java">/*** 测试方法1:根据id查询用户*/@Testpublic void testFindById(){System.out.println("查询结果:"+accountService.selectById(3));}

<2>测试方法2:查询所有用户。(注解@Test)
java"> /*** 测试方法2:查询所有用户*/@Testpublic void testFindAll(){System.out.println("查询结果:"+accountService.selectAll());}

<3>最终完善后的测试类代码(AccountServiceTest)。
java">package com.hyl;import com.hyl.config.SpringConfig;
import com.hyl.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/*** 测试业务层接口方法*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {@Autowiredprivate AccountService accountService;/*** 测试方法1:根据id查询用户*/@Testpublic void testFindById(){System.out.println("查询结果:"+accountService.selectById(3));}/*** 测试方法2:查询所有用户*/@Testpublic void testFindAll(){System.out.println("查询结果:"+accountService.selectAll());}}

<4>单元测试方法1、2的运行结果。



  • 到这里就成功完成了Spring整合JUnit+MyBatis的基本学习了。

http://www.ppmy.cn/ops/162906.html

相关文章

Android Binder 用法详解

Binder 是 Android 系统中的一种进程间通信&#xff08;IPC&#xff09;机制&#xff0c;它允许不同进程之间进行高效通信。Binder 在 Android 系统中被广泛使用&#xff0c;例如在 Activity 与 Service 的交互中。 Binder 的基本组成 实现 Binder 通信通常包含以下几个关键部…

如何在netlify一键部署静态网站

1. 准备你的项目 确保你的静态网站文件&#xff08;如 HTML、CSS、JavaScript、图片等&#xff09;都在一个文件夹中。通常&#xff0c;项目结构如下&#xff1a; my-static-site/ ├── index.html ├── styles/ │ └── styles.css └── scripts/└── script.js…

分类预测 | Matlab实现GWO-LSSVM灰狼算法优化最小二乘支持向量机多特征分类预测

分类预测 | Matlab实现GWO-LSSVM灰狼算法优化最小二乘支持向量机多特征分类预测 目录 分类预测 | Matlab实现GWO-LSSVM灰狼算法优化最小二乘支持向量机多特征分类预测分类效果基本介绍程序设计参考资料 分类效果 基本介绍 1.Matlab实现GWO-LSSVM灰狼算法优化最小二乘支持向量机…

矩阵的奇异值(SVD)分解和线性变换

矩阵的奇异值&#xff08;SVD&#xff09;分解和线性变换 SVD定义 奇异值分解&#xff08;Singular Value Decomposition&#xff0c;简称 SVD&#xff09;是一种重要的线性代数工具&#xff0c;能够将任意矩阵 ( A ∈ R m n \mathbf{A} \in \mathbb{R}^{m \times n} A∈Rmn…

ubuntu中ollama设置记录

自己同一台电脑主机安装3080和3090显卡&#xff0c;测试发现ollama只默认跑在3090上&#xff1b;故查看一下设置&#xff0c;成功也把3080也运行起来了。 原因如下&#xff1a; 开始设置记录&#xff1a; Environment Variables: OLLAMA_DEBUG 作用&#xff1a;显示额外的调试…

【R语言】PCA主成分分析

使用R语言手动实现PCA主成分分析计算&#xff0c;通过计算协方差矩阵计算出数据的主成分得分&#xff0c;根据的分最高的特征进行得分图的绘制 # 读取数据raw_data <- read.csv("R可视化/data.csv", header TRUE, fileEncoding "GBK")new_data <-…

【C】链式二叉树算法题1 -- 单值二叉树

leetcode链接https://leetcode.cn/problems/univalued-binary-tree/description/ 1 题目描述 如果二叉树每个节点都具有相同的值&#xff0c;那么该二叉树就是单值二叉树。只有给定的树是单值二叉树时&#xff0c;才返回 true&#xff1b;否则返回 false。 示例 1&#xff1…

大模型微调入门(Transformers + Pytorch)

目标 输入&#xff1a;你是谁&#xff1f; 输出&#xff1a;我们预训练的名字。 训练 为了性能好下载小参数模型&#xff0c;普通机器都能运行。 下载模型 # 方式1&#xff1a;使用魔搭社区SDK 下载 # down_deepseek.py from modelscope import snapshot_download model_…