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

相关推荐
程序员cxuan37 分钟前
Codex 会把磁盘给烧了?完整复盘来了!
人工智能·后端·程序员
ClouGence1 小时前
Oracle 数据同步为什么会出现数据不一致?长事务是常被忽略的原因
数据库·后端·oracle
快乐肚皮2 小时前
深入理解Loop Engineering
前端·后端
小兔崽子去哪了2 小时前
Vue3 + Pinia 集成 IGV.js 实现 BAM 文件在线浏览
javascript·vue.js·后端
孟陬2 小时前
Claude Code 巧思 `Ctrl+S` 暂存键
前端·后端
雪隐2 小时前
个人电脑玩AI-06让5060 Ti给你打工——不光能画画,Qwen3-TTS还能学人说话,连我老板都信了!
人工智能·后端·python
Oneslide3 小时前
openEuler 17.1GB Everything ISO 离线本地 DNF 源搭建教程
后端
蝎子莱莱爱打怪3 小时前
那不是我的黑历史,那是我的来时路啊!😭😭
后端·程序员
用户298698530143 小时前
Java 实现 Word 文档文本与图片提取的方法
java·后端
蝎子莱莱爱打怪3 小时前
XZLL-IM干货系列 04|Netty 长连接实战:Pipeline 怎么排、心跳怎么跳、连接怎么管
后端·微服务·面试