当前位置: 首页 > article >正文

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

目录

一、项目环境初始化。

(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)实体类。
package com.hyl.domain;

import lombok.Data;

@Data
public class Account {
    private Integer id;
    private String name;
    private Double money;
}


(4)service层。
  • AccountService接口。
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实现类。
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 {

    @Autowired
    private AccountDao accountDao;

    @Override
    public void save(Account account) {
        accountDao.save(account);
    }

    @Override
    public void update(Account account) {
        accountDao.update(account);
    }

    @Override
    public void delete(Integer id) {
        accountDao.delete(id);
    }

    @Override
    public Account selectById(Integer id) {
        return accountDao.selectById(id);
    }

    @Override
    public List<Account> selectAll() {
        return accountDao.selectAll();
    }
}

(5)dao层。(Mapper代理模式)
  • AccountDao接口。
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
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容器中,供其他组件使用。
     */
    @Bean
    public DataSource dataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(userName);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }
}

(7)MyBatis配置类。
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 {

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){

        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();

        //代替Mybatis核心配置文件标签<typeAliases>
        ssfb.setTypeAliasesPackage("com.hyl.domain");

        //因为Jdbc配置类的方法使用了@Bean注解生产DataSource对象的方法。
        // 则可以使用形参注入DataSource。再通过方法设置使DataSource
        ssfb.setDataSource(dataSource);

        //jdbc事务管理默认有spring-jdbc依赖处理
        return ssfb;
    }

    //单独方法代替Mybatis核心配置文件标签<Mappers>
    //使用spring整合mybatis提供的类MapperScannerConfigurer完成映射文件的扫描
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        //设置映射在哪些包下
        mapperScannerConfigurer.setBasePackage("com.hyl.dao");
        return mapperScannerConfigurer;
    }
}

(8)Spring配置类。
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的测试。
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的专用类运行器。
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配置类是哪个。
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)
/**
     * 测试方法1:根据id查询用户
     */
    @Test
    public void testFindById(){
        System.out.println("查询结果:"+accountService.selectById(3));
    }

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

<3>最终完善后的测试类代码(AccountServiceTest)。
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 {

    @Autowired
    private AccountService accountService;

    /**
     * 测试方法1:根据id查询用户
     */
    @Test
    public void testFindById(){
        System.out.println("查询结果:"+accountService.selectById(3));
    }

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


}

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



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

http://www.kler.cn/a/569335.html

相关文章:

  • 常见的正则匹配规则
  • 深入解析SQL Server高级SQL技巧
  • 微店商品详情API接口实战指南:从零实现商品数据自动化获取
  • buuctf.web 64-96
  • 计算机毕业设计SpringBoot+Vue.js贸易行业CRM系统(源码+文档+PPT+讲解)
  • flutter 专题 八十二 Flutter路由框架Fluro简介
  • Immich自托管服务的本地化部署与随时随地安全便捷在线访问数据
  • 专线物流公共服务平台:全面提升专线物流效率
  • 《认知·策略·跃迁:新能源汽车工程师的深度学习系统构建指南》
  • Odoo免费开源CRM技术实战:从商机线索关联转化为售后工单的应用
  • 203、【数组】NLP分词实现(Python)
  • Wireshark插件开发实战:扩展网络协议分析的边界
  • cursor 弹出在签出前,请清理仓库工作树 窗口
  • C++ STL(五) 无序关联容器
  • vue3:三项目增加404页面
  • 记录一次MySQL的分库分表行为
  • Windows逆向工程入门之MASM数据结构使用
  • 数据挖掘与数据分析
  • 【前端知识】Vue2.x与3.x之间的区别以及升级过程需要关注的地方
  • 数据结构(初阶)(七)----树和二叉树(堆,堆排序)