Spring整合JUnit

说明:Spring整合JUnit是指将Spring框架与JUnit测试框架相结合,以便在测试过程中能够利用Spring的功能和特性。

1.导入依赖

复制代码
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>5.2.10.RELEASE</version>
</dependency>

2. 配置

说明:设置类运行器,设置Spring环境对应的配置类。

//设置类运行器 专用运行器

@RunWith(SpringJUnit4ClassRunner.class)

//设置Spring环境对应的配置类

@ContextConfiguration(classes = SpringConfig.class)

3.装配bean

java 复制代码
   //支持自动装配注入bean
    @Autowired
    private AccountService accountService;

    @Test
    public void testFindById(){
        System.out.println(accountService.findById(1));

    }

4.源码

java 复制代码
package com.itheima.service;

import com.itheima.config.SpringConfig;
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)
//设置Spring环境对应的配置类
@ContextConfiguration(classes = SpringConfig.class)
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());
    }


}
相关推荐
陌上丨1 小时前
Redis的Key和Value的设计原则有哪些?
数据库·redis·缓存
AI_56781 小时前
AWS EC2新手入门:6步带你从零启动实例
大数据·数据库·人工智能·机器学习·aws
ccecw1 小时前
Mysql ONLY_FULL_GROUP_BY模式详解、group by非查询字段报错
数据库·mysql
JH30732 小时前
达梦数据库与MySQL的核心差异解析:从特性到实践
数据库·mysql
数据知道2 小时前
PostgreSQL 核心原理:如何利用多核 CPU 加速大数据量扫描(并行查询)
数据库·postgresql
麦聪聊数据3 小时前
Web 原生架构如何重塑企业级数据库协作流?
数据库·sql·低代码·架构
未来之窗软件服务3 小时前
数据库优化提速(四)新加坡房产系统开发数据库表结构—仙盟创梦IDE
数据库·数据库优化·计算机软考
Goat恶霸詹姆斯4 小时前
mysql常用语句
数据库·mysql·oracle
大模型玩家七七5 小时前
梯度累积真的省显存吗?它换走的是什么成本
java·javascript·数据库·人工智能·深度学习
曾经的三心草5 小时前
redis-9-哨兵
数据库·redis·bootstrap