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

相关推荐
❀͜͡傀儡师2 小时前
Spring Boot Pf4j模块化能力设计思考
运维·spring boot·后端·pf4j
前路不黑暗@2 小时前
Java项目:Java脚手架项目的通用组件的封装(五)
java·开发语言·spring boot·学习·spring cloud·bootstrap·maven
❀͜͡傀儡师3 小时前
基于mybatis-plus进行加解密 Spring Boot Starter
spring boot·oracle·mybatis
星空彼岸0074 小时前
SA-Token在SpringBoot中的实战指南
java·spring boot·后端
闻哥4 小时前
ConcurrentHashMap 1.7 源码深度解析:分段锁的设计与实现
java·开发语言·jvm·spring boot·面试·jdk·hash
哈库纳玛塔塔4 小时前
dbVisitor 统一数据库访问库,更新 v6.7.0,面向 AI 支持向量操作
数据库·spring boot·orm
树獭叔叔4 小时前
大模型行为塑造:SFT 与 LoRA 深度解析
后端·aigc·openai
Ivanqhz4 小时前
半格与数据流分析的五个要素(D、V、F、I、Λ)
开发语言·c++·后端·算法·rust
一 乐7 小时前
林业资源管理|基于java + vue林业资源管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·林业资源管理系统