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 单元测试框架。它主要用于编写和运行可重复的自动化测试,帮助开发者验证代码的正确性。是后期开发非常值得学习和使用的一个技术。

一、项目环境初始化。


(1)数据库与数据表。

(2)pom文件中的核心依赖坐标。
XML 复制代码
<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 {

    @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接口。
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文件。
XML 复制代码
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容器中,供其他组件使用。
     */
    @Bean
    public 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 {

    @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配置类。
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核心依赖坐标。

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

(2)导入Spring整合JUnit核心依赖坐标。
XML 复制代码
<!-- 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查询用户
     */
    @Test
    public void testFindById(){
        System.out.println("查询结果:"+accountService.selectById(3));
    }

<2>测试方法2:查询所有用户。(注解@Test)
java 复制代码
 /**
     * 测试方法2:查询所有用户
     */
    @Test
    public 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 {

    @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的基本学习了。
相关推荐
码熔burning1 小时前
(十 五)趣学设计模式 之 命令模式!
java·设计模式·命令模式
gentle coder2 小时前
【框架】Spring、SpringBoot和SpringCloud区别
spring boot·spring·spring cloud
计算机-秋大田4 小时前
基于Spring Boot的乡村养老服务管理系统设计与实现(LW+源码+讲解)
java·vue.js·spring boot·后端·课程设计
盖盖衍上4 小时前
Java 泛型(Generics)详解与使用
java·开发语言·windows
没有十八岁5 小时前
云创智城YunCharge 新能源二轮、四轮充电解决方案(云快充、万马爱充、中电联、OCPP1.6J等多个私有单车、汽车充电协议)之新能源充电行业系统说明书
java·数据库·spring·汽车
小萌新上大分5 小时前
Minio搭建并在SpringBoot中使用完成用户头像的上传
java·spring boot·后端·minio·minio搭建·头像上传·minio入门
B站计算机毕业设计超人6 小时前
计算机毕业设计SpringBoot+Vue.js校园失物招领系统(源码+文档+PPT+讲解)
java·vue.js·spring boot·后端·毕业设计·课程设计·毕设
计算机-秋大田6 小时前
基于SpringBoot的环保网站的设计与实现(源码+SQL脚本+LW+部署讲解等)
java·vue.js·spring boot·后端·课程设计
汤姆yu6 小时前
基于springboot的高校物品捐赠系统
java·spring boot·后端·高校物品捐赠
magic 2456 小时前
深入理解Java网络编程:从基础到高级应用
java·开发语言