天天看点

Spring整合MyBatis及Junit4.11报错:No tests found matching [{ExactMatcher:fDisplayName=testFindById]...

发生缘由

  • 复习Spring整合MyBatis及Junit

运行环境

  • VSCode版本:1.72.0 (user setup)
  • jdk版本:jdk-8
  • 电脑系统:win10
  • spring-context:5.2.10.RELEASE
  • junit:4.11
  • spring-test:5.2.10.RELEASE
  • lombok:1.18.24
  • druid:1.1.16
  • mybatis:3.5.7
  • mysql-connector-java:8.0.30
  • spring-jdbc:5.2.10.RELEASE
  • mybatis-spring:1.3.0

环境搭建

搭建MyBatis环境

# 数据库操作
# 如果不存在linxuan数据库那么就创建
CREATE DATABASE IF NOT EXISTS linxuan CHARACTER SET utf8;
# 使用linxuan数据库
USE linxuan;
# 如果不存在tb_account表那么就创建
CREATE TABLE IF NOT EXISTS tb_account(
    id INT PRIMARY KEY AUTO_INCREMENT,
    NAME VARCHAR(35),
    money DOUBLE
);
# 删除当前表,并创建一个新表 字段相同。用来清除当前表的所有数据
TRUNCATE TABLE tb_account;
# 插入数据
INSERT INTO tb_account VALUES(NULL, "林炫", 10000), (NULL, "陈沐阳", 20000);
# 查询数据
SELECT * FROM tb_account;
           
<!-- 项目pom.xml导入依赖 -->
<dependencies>
    <!-- Lombok简化开发 -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.24</version>
    </dependency>
    <!-- druid连接池技术 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.16</version>
    </dependency>
    <!-- mybatis依赖 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>
    <!-- mysql驱动jar包 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.30</version>
    </dependency>
</dependencies>
           
package com.linxuan.pojo;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {
    private Integer id;
    private String name;
    private Double money;
}
           
package com.linxuan.dao;

/**
 * Dao接口相当于之前在Mybatis中学过的mapper接口,去掉了Mybatis-config.xml文件
 * 直接将实现查询的SQL语句用注解的形式在这里编写,当然如果比较复杂的查询方式还是要使用配置文件方式
 */
public interface AccountDao {
    @Insert("insert into tb_account(name,money)values(#{name}, #{money})")
    void save(Account account);

    @Delete("delete from tb_account where id = #{id} ")
    void delete(Integer id);

    @Update("update tb_account set name = #{name} , money = #{money} where id = #{id} ")
    void update(Account account);

    @Select("select * from tb_account")
    List<Account> findAll();

    @Select("select * from tb_account where id = #{id} ")
    Account findById(Integer id);
}
           
package com.linxuan.service;

public interface AccountService {

    /**
     * 插入数据
     * @param account
     */
    void save(Account account);

    /**
     * 根据id删除数据
     * @param id
     */
    void delete(Integer id);

    /**
     * 根据id修改数据
     * @param account
     */
    void update(Account account);
    
    /**
     * 根据id查询数据
     * @param id
     * @return
     */
    Account findById(Integer id);

    /**
     * 查询所有数据
     * @return
     */
    List<Account> findAll();
}      
           
package com.linxuan.service.impl;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    /**
     * 插入数据
     */
    public void save(Account account) {
        accountDao.save(account);
    }

    /**
     * 删除数据
     */
    public void delete(Integer id) {
        accountDao.delete(id);
    }

    /**
     * 更新数据
     */
    public void update(Account account){
        accountDao.update(account);
    }

    /**
     * 根据ID查询数据
     */
    public Account findById(Integer id) {
        return accountDao.findById(id);
    }

    /**
     * 查询所有数据
     */
    public List<Account> findAll() {
        return accountDao.findAll();
    }
}
           
# resources目录下面创建一个jdbc.properties文件,添加对应键值对
# MySQL8驱动为com.mysql.cj.jdbc.Driver,之前的是com.mysql.jdbc.Driver
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/linxuan?useSSL=false
jdbc.username=root
jdbc.password=root
           

resources目录下创建MyBatis的核心配置文件,习惯上命名为

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!-- 读取外部properties配置文件 -->
    <properties resource="jdbc.properties"></properties>
    <!-- 设置连接数据库的环境 使用development环境 -->
    <environments default="development">
        <!-- 设置该数据库环境id为development -->
        <environment id="development">
            <!-- JDBC设置当前环境的事务管理都必须手动处理,MANAGED设置事务被管理 -->
            <transactionManager type="JDBC"/>
            <!-- type="POOLED"使用数据库连接池,会将创建的连接进行缓存,下次使用可以从缓存中直接获取 -->
            <!-- type="UNPOOLED"不使用数据库连接池,即每次使用连接都需要重新创建 -->
            <!-- type="JNDI" 调用上下文中的数据源 -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 映射文件扫描包路径 虽然这里没有用到配置文件的方式,但是也需要导入,否则报错 -->
    <mappers>
        <package name="com.linxuan.dao"></package>
    </mappers>
</configuration>
           
public static void main(String[] args) throws IOException {
    // 1. 创建SqlSessionFactoryBuilder对象
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
    // 2. 加载SqlMapConfig.xml配置文件
    InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    // 3. 创建SqlSessionFactory对象
    SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
    // 4. 获取SqlSession
    SqlSession sqlSession = sqlSessionFactory.openSession();
    // 5. 执行SqlSession对象执行查询,获取结果User
    AccountDao accountDao = sqlSession.getMapper(AccountDao.class);

    Account ac = accountDao.findById(1);
    System.out.println(ac);

    // 6. 释放资源
    sqlSession.close();
}
// Account(id=1, name=林炫, money=10000.0)
           

Spring整合MyBatis

<!-- 导入依赖 -->
<dependencies>
    <!-- Spring依赖环境 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.10.RELEASE</version>
    </dependency>
    <!-- Spring操作数据库需要该jar包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.10.RELEASE</version>
    </dependency>
    <!-- Spring与Mybatis整合的jar包,这个jar包mybatis在前面,是Mybatis提供的-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.0</version>
    </dependency>
</dependencies>
           
// 加载配置文件,读取值。如果不加载,那么@Value就无法获取值。
@PropertySource("classpath:jdbc.properties")
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;

    // 制作bean,交由Spring管理
    @Bean
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }
}
           
package com.linxuan.config;

public class MybatisConfig {

    // 定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象
    // 这里的dataSource会自动装配进去,我们不用管
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        // 设置模型类的别名扫描,这个等于<typeAliases><package name="com.linxuan.pojo"></typeAliases>
        ssfb.setTypeAliasesPackage("com.linxuan.pojo");
        // 设置数据源
        ssfb.setDataSource(dataSource);
        return ssfb;
    }

    // 定义bean,返回MapperScannerConfigurer对象
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        // MapperScannerConfigurer对象处理原始配置文件中的mappers相关配置,加载数据层的Mapper接口类
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        // 用来设置所扫描的包路径,等于配置文件中<mappers><package name="com.linxuan.dao"></package>
        msc.setBasePackage("com.linxuan.dao");
        return msc;
    }
}
           
// 定义该类为配置类
@Configuration
// 包扫描路径,主要需要扫描Service包下面AccountServiceImpl类上面的@Service注解
@ComponentScan("com.linxuan")
// 引入其他配置类
@Import({JdbcConfig.class, MybatisConfig.class})
public class SpringConfig {
}
           
public static void main(String[] args) {
    // 获取SpringIOC容器
    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    AccountService accountService = ctx.getBean(AccountService.class);
    Account ac = accountService.findById(1);
    System.out.println(ac);
}
// 二月 05, 2023 7:09:43 下午 com.alibaba.druid.support.logging.JakartaCommonsLoggingImpl info
// 信息: {dataSource-1} inited
// Account(id=1, name=林炫, money=10000.0)
           

Spring整合Junit

<!-- 导入依赖 -->
<dependencies>
    <!-- Junit单元测试 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
    <!-- Spring整合Junit依赖的jar包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.2.10.RELEASE</version>
    </dependency>
</dependencies>
           
package com.linxuan.test;

//设置类运行器
@RunWith(SpringJUnit4ClassRunner.class)
// 加载配置类,设置Spring环境对应的配置类
@ContextConfiguration(classes = {SpringConfig.class})
// 加载配置文件
// @ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class AccountServiceTest {
    //支持自动装配注入bean
    @Autowired
    private AccountService accountService;
    
    @Test
    public void testFindById(){
        System.out.println(accountService.findById(1));
    }
    
    @Test
    public void testFindAll(){
        System.out.println(accountService.findAll());
    }
}
           

报错信息

运行

testFindById

方法会报错:

java.lang.Exception: No tests found matching [{ExactMatcher:fDisplayName=testFindById], {ExactMatcher:fDisplayName=testFindById(com.linxuan.test.AccountServiceTest)], {LeadingIdentifierMatcher:fClassName=com.linxuan.test.AccountServiceTest,fLeadingIdentifier=testFindById]] from [email protected]
           
Spring整合MyBatis及Junit4.11报错:No tests found matching [{ExactMatcher:fDisplayName=testFindById]...

解决方案

经测试,将Junit依赖版本升级即可。这里使用的是

4.11

版本的,如果升级到

4.12

及以上是没有任何问题的。

<!-- Junit单元测试 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>