单元测试
使用Spring Boot进行开发,就会涉及到做单元测试,而Spring Boot帮我们集成了单元测试框架JUnit5,在我们创建完一个Spring Boot项目之后,可以直接使用Spring Boot整合的单元测试功能
基本使用
使用单元测试功能,需要以下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
这个依赖一般创建完Spring Boot项目就会自动导入,默认使用范围是项目的test路径下
然后在test包下创建一个测试类,并在测试类的方法上添加@Test注解
class MyTest {
@Test
void contextLoads() {
System.out.println("启动测试方法");
}
}
在IDE中启动测试方法

不过测试方法是没有在Spring环境中运行的,如果需要使用IOC容器,声明式事务等功能,则需要在测试类上添加@SpringBootTest注解
@SpringBootTest
class MyTest {
@Autowired
UserMapper userMapper;
@Test
void con

本文介绍了如何在Spring Boot项目中进行单元测试,详细讲解了JUnit5的基本使用和常用注解,如@DisplayName、@BeforeEach、@AfterEach、@BeforeAll、@AfterAll、@RepeatedTest、@Disabled和@Timeout,帮助开发者更好地理解和应用单元测试。
最低0.47元/天 解锁文章
722

被折叠的 条评论
为什么被折叠?



