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


}
相关推荐
字节源流12 分钟前
【MYSQL】索引篇(一)
数据库·mysql
n33(NK)17 分钟前
MySQL中count(1)和count(*)的区别及细节
数据库·mysql
heart000_11 小时前
MySQL高级查询技巧:分组、聚合、子查询与分页【MySQL系列】
数据库·mysql
会敲键盘的猕猴桃很大胆2 小时前
Redis实战-基于redis和lua脚本实现分布式锁以及Redission源码解析【万字长文】
java·redis·分布式·spring·lua
凭君语未可3 小时前
MySQL中COUNT(*)、COUNT(1)和COUNT(字段名)的深度剖析与实战应用
数据库·mysql
z人间防沉迷k3 小时前
MySQL事务和索引原理
数据库·笔记·sql·mysql
z人间防沉迷k3 小时前
字符串索引、幻读的解决方法
数据库·sql·mysql
xiaohezi3 小时前
Milvus 向量数据库快速入门(人话版)
数据库
shangjg33 小时前
Kafka ACK机制详解:数据可靠性与性能的权衡之道
java·数据库·分布式·后端·kafka
岁忧4 小时前
LeetCode 高频 SQL 50 题(基础版)之 【聚合函数】部分
数据库·sql·leetcode