springboot test_spring boot 学习笔记2(单元测试)

单元测试

开发中,每当完成一个功能接口或业务方法的编写后,通常都会借助单元测试验证该功能是否正确。 Spring Boot对项目的单元测试提供了很好的支持,在使用时,需要提前在项目的pom.xml文件中添加 spring-boot-starter-test测试依赖启动器,可以通过相关注解实现单元测试

演示:

  • 添加spring-boot-starter-test测试依赖启动器

在项目的pom.xml文件中添加spring-boot-starter-test测试依赖启动器,示例代码如下:

org.springframework.boot

spring-boot-starter-test

test

注意:使用Spring Initializr方式搭建的Spring Boot项目,会自动加入spring-boot-starter-test测试依赖 启动器,无需再手动添加

  • 编写单元测试类和测试方法

使用Spring Initializr方式搭建的Spring Boot项目,会在src.test.java测试目录下自动创建与项目主程序 启动类对应的单元测试类

@RunWith(SpringRunner .class) // 测试启动器,并加载 Spring Boot 测试注解

@SpringBootTest //标记为Spring Boot单元测试类,并加载项目的Applicationcontext上下 文环境

class SpringbootDemoApplicationTests {

@Autowired

private DemoController demoController;

//自动创建的单元测试方法实例

@Test

void contextLoads() {

String demo = demoController.demo();

System.out.println(demo);

}

}

上述代码中,先使用@Autowired注解注入了 DemoController实例对象,然后在contextLoads()方法中 调用了DemoController类中对应的请求控制方法contextLoads(),并输出打印结果

fa21a171dca3f160d12703ff05303aec.png

打印结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值