【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,运行结果:

相关推荐
♡喜欢做梦14 小时前
Spring IOC
java·后端·spring
葡萄城技术团队1 天前
迎接下一代 React 框架:Next.js 16 核心能力解读
javascript·spring·react.js
灰小猿1 天前
Spring前后端分离项目时间格式转换问题全局配置解决
java·前端·后端·spring·spring cloud
知其然亦知其所以然1 天前
这波AI太原生了!SpringAI让PostgreSQL秒变智能数据库!
后端·spring·postgresql
zhaomx19891 天前
Spring 事务管理 Transaction rolled back because it has been marked as rollback-only
数据库·spring
曹朋羽1 天前
Spring EL 表达式
java·spring·el表达式
亚林瓜子1 天前
Spring中的异步任务(CompletableFuture版)
java·spring boot·spring·async·future·异步
neoooo2 天前
⚙️ Spring Boot × @RequiredArgsConstructor:写出最干净的依赖注入代码
spring boot·后端·spring
好好研究2 天前
Spring框架 - 开发方式
java·后端·spring
编啊编程啊程2 天前
【029】智能停车计费系统
java·数据库·spring boot·spring·spring cloud·kafka