【Spring整合Junit】Spring整合Junit介绍

本文内容基于【Spring整合MyBatis】Spring整合MyBatis的具体方法进行测试

文章目录

  • [1. 导入相关坐标](#1. 导入相关坐标)
  • [2. 使用Junit测试所需注解](#2. 使用Junit测试所需注解)
  • [3. 在测试类中写相关内容](#3. 在测试类中写相关内容)

1. 导入相关坐标

在pom.xml中导入相关坐标:

xml 复制代码
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.3.25</version>
</dependency>

2. 使用Junit测试所需注解

一般测试Service类,我们在test包下建立测试类,并使用@Runwith来指定运行期,通过@ContextConfiguration来指定配置类

java 复制代码
package com.example.project2.service;

import com.example.project2.config.SpringConfig;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {
}

关于@Runwith找了两篇博客:

  1. Junit的基础讲解一
  2. Junit的基础讲解二

3. 在测试类中写相关内容

使用依赖注入在这里注入accountService,在测试方法中上需要加上@Test的注解

java 复制代码
package com.example.project2.service;

import com.example.project2.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)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {

    @Autowired
    private AccountService accountService;

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

运行结果:

findById()中的id改成2,运行结果:

相关推荐
qq_1851986916 小时前
(Spring Bean + delegateExpression)实现http服务 的完整可运行项目
spring
Ai拆代码的曹操17 小时前
Spring 事务 REQUIRES_NEW 嵌套调用:连接池翻倍的秘密
java·后端·spring
wear工程师1 天前
WebFlux 里能不能直接 block?面试别只答「不能」
spring
凤山老林1 天前
SpringBoot 3 启用 spring.factories 后如何升级替换原有的 spring.factories ?
spring boot·后端·spring
小罗水1 天前
第1章 大模型、企业知识库与 RAG 平台概述
java·spring
qq_185198691 天前
骆驼任务Flowable + Apache Camel 集成
spring·apache·flowable
lichuangcsdn1 天前
【Spring AI 学习(一)】spring ai是什么
人工智能·学习·spring·spring ai
吃饱了得干活2 天前
@Transactional 又失效了?把这 8 个坑全填了!
java·后端·spring
今天AI了吗2 天前
Spring AI 框架实战:Java 后端集成大模型的架构设计与工程落地
java·人工智能·python·spring·机器学习
乐观的Terry2 天前
9、发布系统-Webhook自动发布
java·spring boot·spring·spring cloud·mybatis