Springboot项目的测试类书写(速通)

目录

  • 前言
  • [1. 单元测试的测试类](#1. 单元测试的测试类)
  • [2. 框架测试的测试类](#2. 框架测试的测试类)

前言

在实际开发中,如果只是做一个简单的单元测试(不涉及端到端、数据库交互、API调用、消息队列处理等),我为了方便一般都是找块儿地方写一个main方法来跑一下就行了,当然不推荐这样做,怕被领导发现 。所以还是建议在 /src/test/xxx/ 目录下写一个测试类来做测试。

1. 单元测试的测试类

如果只是为了做一个单元测试,比如说测试一个方法是否能正常跑,那么可以按照以下流程创建一个:

  1. maven依赖

    xml 复制代码
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
  2. 测试类

    java 复制代码
    import org.junit.Test;
    
    public class MyTest {
        @Test
        public void test() {
            long l = System.currentTimeMillis();
            System.out.println(l);
        }
    }

要求:

  1. 测试类中的方法需要加上@Test
  2. 访问修饰符必须是public,返回类型必须是void
  3. 不接受任何参数(JUnit5可以用@ParameterizedTest来实现参数化测试,但是很麻烦);
  4. 可用expected来标注需要捕获的异常@Test(expected = ExceptionType.class)

2. 框架测试的测试类

如果需要启动所有上下文进行测试,那么在测试类上面加一个@SpringBootTest就行了,接着就可以使用Bean做测试了,如下:

java 复制代码
@SpringBootTest
public class ConfEncTest {
    @Autowired
    private StringEncryptor jasyptStringEncryptor;
	
	@Test
	public void encryptTest() {
		String originPassord = "123456";
        String encryptStr = jasyptStringEncryptor.encrypt( originPassord );
        System.out.println(encryptStr);
    }
 }

@SpringBootTest:启动一个全功能的Spring Boot应用上下文来进行集成测试,可以使用所有的Bean。启动一个测试方法就相当于启动整个项目,比较慢。

如果只是使用几个Bean,那么可以使用 @RunWith(SpringRunner.class) + @ContextConfiguration

java 复制代码
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {StringEncryptor.class})
public class ConfEncTest {
    @Autowired
    private StringEncryptor jasyptStringEncryptor;
	
	@Test
	public void encryptTest() {
		String originPassord = "123456";
        String encryptStr = jasyptStringEncryptor.encrypt( originPassord );
        System.out.println(encryptStr);
    }
 }

@RunWith:用于指定运行测试类的测试运行器(Test Runner),需要搭配@ContextConfiguration使用。

SpringRunner: Spring提供的一个特殊的测试运行器,它负责解析@SpringBootTest、@ContextConfiguration等Spring相关的注解,并在测试执行前创建和配置Spring应用上下文。

@ContextConfiguration:指定包含所需Bean定义的配置类或XML配置文件。这样,SpringRunner在运行测试时,会根据@ContextConfiguration提供的信息来创建一个包含必要Bean的ApplicationContext,从而实现对这些依赖的注入。如果需要同时指定多个类可以这样写:@ContextConfiguration(classes = {ConfigA.class, ConfigB.class, ConfigC.class})。

@SpringBootTest是一个复合注解,其中包含了@RunWith。

相关推荐
武昌库里写JAVA36 分钟前
39.剖析无处不在的数据结构
java·vue.js·spring boot·课程设计·宠物管理
画个大饼2 小时前
Go语言实战:快速搭建完整的用户认证系统
开发语言·后端·golang
李白的粉6 小时前
基于springboot的在线教育系统
java·spring boot·毕业设计·课程设计·在线教育系统·源代码
小马爱打代码7 小时前
SpringBoot原生实现分布式MapReduce计算
spring boot·分布式·mapreduce
iuyou️7 小时前
Spring Boot知识点详解
java·spring boot·后端
一弓虽7 小时前
SpringBoot 学习
java·spring boot·后端·学习
姑苏洛言7 小时前
扫码小程序实现仓库进销存管理中遇到的问题 setStorageSync 存储大小限制错误解决方案
前端·后端
光而不耀@lgy8 小时前
C++初登门槛
linux·开发语言·网络·c++·后端
方圆想当图灵8 小时前
由 Mybatis 源码畅谈软件设计(七):SQL “染色” 拦截器实战
后端·mybatis·代码规范
毅航8 小时前
MyBatis 事务管理:一文掌握Mybatis事务管理核心逻辑
java·后端·mybatis