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


}
相关推荐
dapeng28701 分钟前
机器学习与人工智能
jvm·数据库·python
spencer_tseng4 分钟前
java.lang.ClassNotFoundException: org.slf4j.Logger
java·spring·maven
洛兮银儿8 分钟前
如何用python连接mysql数据库?
数据库·mysql
CDN36010 分钟前
MySQL安全加固十大硬核操作及CDN的隐形守护
数据库·mysql·安全
小江的记录本12 分钟前
【VO、DTO、Entity】VO、DTO、Entity三大核心数据对象全解析(附核心对比表 + 代码示例)
java·数据库·spring boot·spring·架构·mybatis·数据库架构
不想看见40423 分钟前
Qt 框架中的信号与槽机制【详解】
服务器·数据库·qt
白鸽梦游指南31 分钟前
redis-cluster集群实验及解析
数据库·redis·缓存
SuniaWang32 分钟前
《Spring AI + 大模型全栈实战》学习手册系列·专题一:《RAG技术全景解析:从原理到架构设计》
java·javascript·人工智能·spring boot·后端·spring·架构
java1234_小锋32 分钟前
Java高频面试题:Spring是如何解决Bean的循环依赖?
java·开发语言·spring
阿贵---35 分钟前
构建一个基于命令行的待办事项应用
jvm·数据库·python