SpringBoot junit单元测试

本文介绍了如何在SpringBoot项目中使用junit进行单元测试。首先,需要确保pom.xml中添加了spring-boot-starter-test依赖。接着,通过@SpringBootTest注解启动SpringBoot支持,并利用Junit的基本注解进行测试。在测试类中,可以使用@Value注解获取配置文件的属性值,无需编写controller即可测试业务逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot项目的快速搭建可参考:构建SpringBoot项目 (分为两部分:第一部分是project的基本信息,根据当前开发环境选择;第二部是扩展部分,添加不同的jar包支持。生成项目之后直接导入本地开发工具即可)。

SpringBoot 支持junit单元测试,编写测试类之前需要添加spring-boot-starter-test 依赖,如果构建项目时已添加直接忽略这一步,pom中添加依赖:

     <!-- 单元测试jar -->
     <dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
     </dependency>
接下来新建测试类TestFileInfoService:

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = Application.class)
    public class TestFileInfoService {

         @Autowired
         private FileInfoService fileInfoService;
 
         @Test
         public void TestGetFileList() {
             List<FileVO> list = fileInfoService.getFileList();
             Assert.assertTrue(list.size() == 4);
         }
   }
@RunWith :SpringJunit支持

@SpringBootTest : SpringBoot启动支持,Application为工程的启动类

Junit的基本注解和用法在这里基本上都支持,配置文件的属性值可以直接用@Value注解获取,例如:

    @Value("${spring.mail.username}")
    private String from;

为测试类添加@RunWith和@SpringBootTest两个注解之后就可以进行Junit测试了,这样可以在不用编写controller类的情况下进行业务逻辑的测试。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值