JAVA-springboot JUnit单元测试

SpringBoot从入门到精通-第9章 JUnit单元测试

一、JUnit与单元测试

JUnit是一个开源的测试框架,虽然可以用于测试大多数编程语言的应用程序,但特别适合用于测试Java语言的应用程序。
软件测试一般分为4个阶段,即单元测试、集成测试、系统测试和验收测试。JUnit主要用于单元测试,是需要在开发工具中编写代码完成的。

二、Springboot中的JUnit

在Spring Boot项目的spring-boot-starter-test依赖中,已经包含了JUnit,每个Spring Boot项目都自带src/test/java目录,该目录专门用于存放单元测试类。
在这里插入图片描述
依赖在创建springboot时候就已经有了

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
    </parent>

    <groupId>com.mr</groupId>
    <artifactId>springboot_crud</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.6</version>
        </dependency>

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

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <!--			<version>8.0.16</version>-->
            <scope>runtime</scope>
        </dependency>

<!--        <dependency>-->
<!--            <groupId>mysql</groupId>-->
<!--            <artifactId>mysql-connector-java</artifactId>-->
<!--            <version>5.1.34</version>-->
<!--            <scope>runtime</scope>-->
<!--        </dependency>-->

<!--        <dependency>-->
<!--            <groupId>org.mariadb.jdbc</groupId>-->
<!--            <artifactId>mariadb-java-client</artifactId>-->
<!--            <version>2.7.3</version>-->
<!--        </dependency>-->

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

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

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

</project>

三、JUnit注解

3.1重点注解
@SpringBootTest标注测试类
@Test标注测试方法

例:程序默认带的测试类内容

@SpringBootTest
class ApplicationTests {


    @Test
    void contextLoads() {

    }

实例
测试用户登录的验证服务,如果用户名是mr并且密码是123,方法返回true,否则返回false
1、编写步骤

  1. 创建服务层接口写验证方法
  2. 创建服务层接口的实现类,重写服务层接口的方法
  3. 编写测试类执行接口中的方法
    2、步骤附代码
    1、创建服务层接口写验证方法
package com.example._20250605springboot_junit.service;

public interface UserService {
    boolean check(String usernamem,String pasword);
}

2、创建服务层接口的实现类,重写服务层接口的方法

package com.example._20250605springboot_junit.service.impl;

import com.example._20250605springboot_junit.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Override
    public boolean check(String user,String pass){
        return "mr".equals(user) && "123".equals(pass);
    }
}

3、编写测试类执行接口中的方法

package com.example._20250605springboot_junit;

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

@SpringBootTest
class ApplicationTests {

    @Autowired
    private UserService userService;
    @Test
    void contextLoads() {
        String user = "mr",pass = "123";
        System.out.println(user+","+pass);
        System.out.println(userService.check(user,pass));

        String user2 = "mm",pass2 = "111";
        System.out.println(user2 +","+pass2);
        System.out.println(userService.check(user2,pass2));
    }

}

4、点击测试类测试方面前面的运行按钮,运行测试方法
在这里插入图片描述
在这里插入图片描述
查看执行结果
在这里插入图片描述
3.2用于测试前和测试后的注解
@BeforeEach
@AfterEach
@BeforeAll
@AfterAll

3.3参数化测试
@ParameterizedTest注解
该注解必须配合其他参数源注解一同使用
@ValueSource注解
@MethodSource注解
@EnumSource注解

四、断言

五、在单元测试中模拟内置对象

Spring Boot 项目中对 Service 层进行单元测试,通常使用 `spring-boot-starter-test` 提供的依赖,其中包括 JUnit、AssertJ、Hamcrest 等测试库。为了实现对 Service 层的测试,需要结合 Spring 的测试支持,特别是 `@SpringBootTest` 或 `@ContextConfiguration` 来加载 Spring 应用上下文。 以下是一个完整的示例,展示如何使用 JUnit 对 Service 层进行单元测试: ### Service 层测试示例 假设有一个简单的 `UserService`,其依赖于 `UserRepository`,并提供一个获取用户信息的方法。 ```java @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public User getUserById(Long id) { return userRepository.findById(id).orElse(null); } } ``` 对应的测试类可以如下编写: ```java @SpringBootTest public class UserServiceTest { @Autowired private UserService userService; @MockBean private UserRepository userRepository; @Test public void testGetUserById() { User mockUser = new User(1L, "John Doe"); when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser)); User result = userService.getUserById(1L); assertNotNull(result); assertEquals("John Doe", result.getName()); } } ``` ### 关键注解说明 - `@SpringBootTest`:启动完整的 Spring 应用上下文,适合集成测试[^1]。 - `@MockBean`:用于创建和注入模拟对象,避免真实依赖的调用。 - `@Autowired`:自动注入被测试的服务实例。 - `@Test`:JUnit 注解,标记测试方法。 ### Maven 依赖配置 确保 `pom.xml` 中包含以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> ``` ### 测试执行与验证 运行测试时,Spring Boot 会加载上下文并初始化模拟对象。通过 `when(...).thenReturn(...)` 设置模拟行为,然后调用服务方法并验证返回值是否符合预期。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值