SpringBoot项目单元测试

一、新建SpringBoot项目并引入单元测试依赖包

版本和springboot版本保持一致即可

XML 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

完整pom依赖

XML 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.qiu</groupId>
    <artifactId>demo-springboot-web</artifactId>
    <version>1.0-SNAPSHOT</version>
    <description>SpringBoot集成web</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.5.7</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>


    <properties>
        <java.version>21</java.version>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <openapi.version>2.8.14</openapi.version>
    </properties>
    <dependencies>
        <!--web-->
        <!-- 排除默认的 Tomcat -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- 添加 Jetty -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>

        <!-- 添加 Undertow -->
<!--        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>-->



        <!--mysql-->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--openapi-->
        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
            <version>${openapi.version}</version>
        </dependency>

        <!--  JPA -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

        </plugins>
    </build>

</project>

二、test类和方法

2.1.单元测试类所在的包需要和java代码中启动类同一个包或子包中

如果不一致会报以下错误

java 复制代码
com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit5 com.qiu1.UserServiceTest,test1
21:05:27.877 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils -- Could not detect default configuration classes for test class [com.qiu1.UserServiceTest]: UserServiceTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.

Test ignored.

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration by searching packages upwards from the test. You can use @ContextConfiguration, @SpringBootTest(classes=...) or other Spring Test supported mechanisms to explicitly declare the configuration classes to load. Classes annotated with @TestConfiguration are not considered.

	at org.springframework.util.Assert.state(Assert.java:79)
	at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.findConfigurationClass(SpringBootTestContextBootstrapper.java:246)
	at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:233)
	at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.processMergedContextConfiguration(SpringBootTestContextBootstrapper.java:150)
	at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:351)
	at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:267)
	at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:215)
	at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:108)
	at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.buildTestContext(SpringBootTestContextBootstrapper.java:111)
	at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:142)
	at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:126)
	at org.springframework.test.context.junit.jupiter.SpringExtension.getTestContextManager(SpringExtension.java:362)
	at org.springframework.test.context.junit.jupiter.SpringExtension.beforeAll(SpringExtension.java:128)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)


Process finished with exit code -1

原因如下

测试类与主应用类不在同一包或子包下 Spring Boot 默认从测试类所在的包开始向上搜索带有 @SpringBootApplication 或 @SpringBootConfiguration 注解的类。如果测试类和主应用类不在同一个包或子包中,就会导致找不到配置类。

2.2.需要在类上面增加注解@SpringBootTest

如何要测试service方法使用注解@Autowired

java 复制代码
package com.qiu;

import com.qiu.entity.User;
import com.qiu.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.AssertionsKt.assertNotNull;

/**
 * 描述:user测试类
 *
 * @author: qxd
 * @date: 2026/2/9 22:56
 * @version: 1.0.0
 */
@SpringBootTest
public class UserServiceTest {
    // 注入待测试的 service
    @Autowired
    private UserService userService;

    @Test
    void test1() {
        String userName = "qiuxiaodong";
        // 查询数据
        Optional<User> userOptional = userService.findByUsername(userName);
        if(userOptional.isPresent()){
            User user = userOptional.get();
            System.out.println(user.toString());
        }
    }
    @Test
    void test2() {
        // 查询数据
        List<User> allUsers = userService.getAllUsers();
        System.out.println("size:"+ allUsers.size());
        int size = allUsers.size();
        // 断言相等
        assertEquals(1,size);
        // 断言为真
        assertTrue(size > 0);
        // 断言非空
        assertNotNull(size);
        // 断言相等
        assertEquals(2,size);
    }
}

三、访问链接

https://gitee.com/qiuxiaodong/demo

项目名称:demo-springboot-web

相关推荐
程序员爱钓鱼17 小时前
GoHTML解析利器:github.com/PuerkitoBio/goquery实战指南
后端·google·go
golang学习记18 小时前
从“大泥球“到模块化单体:Spring Modulith + IntelliJ IDEA 拯救你的代码
后端·intellij idea
颜酱18 小时前
一步步实现字符串计算器:从「转整数」到「带括号与优化」
javascript·后端·算法
离开地球表面_9918 小时前
金三银四程序员跳槽指南:从简历到面试再到 Offer 的全流程准备
前端·后端·面试
UrbanJazzerati18 小时前
Scrapling入门指南:零基础也能学会的网页抓取神器
后端·面试
张洪权18 小时前
mysql + nest.js 加锁 搞并发问题
后端
郡杰18 小时前
MyBatisPlus
后端
beata18 小时前
Java基础-18:Java开发中的常用设计模式:深入解析与实战应用
java·后端
Qlly18 小时前
DDD 架构为什么适合 MCP Server 开发?
人工智能·后端·架构
苏三说技术18 小时前
Prompt、Agent、Function Call、Skill、MCP,傻傻分不清楚?
后端