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());
    }


}
相关推荐
ggaofeng3 分钟前
自己编写邮件服务器和客户端
数据库
java1234_小锋7 分钟前
【技术专题】Mysql8 数据库 - Mysql8 添加,更新,删除数据
数据库·mysql
PaperData9 分钟前
2015-2024年各省绿色贸易数据
数据库
Wang's Blog22 分钟前
Java框架 SpringCloud 快速入门: Nacos 服务多级存储模型
java·spring·spring cloud
小羊没烦恼!23 分钟前
系统内部模块(子系统)之间的耦合以及模块(子系统)划分
java·开发语言·前端·数据库·算法·c#
麦壳饼1 小时前
深入探讨:SonnetDB 的文件格式与存储布局
数据库·sonnetdb
for_ever_love__2 小时前
Redis 持久化讲透:RDB、AOF 与混合持久化怎么选
java·数据库·redis·持久化·aof·区别·rdb
l1t2 小时前
测试bicdb 20261007提交的0.2版功能
数据库
小码哥0682 小时前
能碳管理系统源码揭秘:避坑指南与实战选型
java·spring·能源·能源管理·能源监测·能碳管理
内存漫游2 小时前
锁与死锁——数据库为什么会发生事务等待?
数据库