【Java】【SpringBoot】CP02:单元测试

This article is written by Xrilang(Chinese Name:萌狼蓝天)

If you want find me ,You can contact me in BiliBili . My Bilibili name is 萌狼蓝天

Of course, you can also add my QQ(My QQ number is: 3447902411)

(Please note that your sole purpose of adding me is limited to technical exchange. I won't help you with your homework!)


萌狼蓝天 - 博客园 | 萌狼工作室 - 萌狼蓝天 (mllt.cc) | 萌狼蓝天の技术栈 | Welcome !

在实际开发中,每当完成一个功能接口或业务方法的编写后,通常都会借助单元测试验证该功能是否正确。

Spring Boot 对项目的单元测试提供了很好的支持,在使用时,需要提前在项目的pom.xml文件中添加spring-boot-starter-test测试依赖启动器,可以通过相关注解实现单元
测试。

添加测试依赖启动器

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

image.png

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

如果是自行添加,务必添加在dependencies范围内

<dependencies>
<!--在此处添加-->
</dependencies>

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

单元测试类

image.png

image.png

/**
 * 使用Spring Initializr方式自动创建的主程序启动类对应的单元测试类
 */

@RunWith(SpringRunner.class) //测试运行器,并加载Spring Boot测试注解
@SpringBootTest //标记单元测试类,并加载项目的上下文环境ApplicationContext
class Edu02CreateMySpringBootProjectApplicationTests {
    //自动创建的单元测试方法示例
    @Test
    void contextLoads() {
    }

}
单元测试方法

image.png

@Autowired //引入HelloController实例对象
    private HelloController helloController;
    @Test
    public void helloControllerTest(){ //新增的单元测试方法
        String hello = helloController.hello();//调用HelloController类中对应的请求控制方法hello()
        System.out.println(hello);//打印输出结果
    }
/**
 * 使用Spring Initializr方式自动创建的主程序启动类对应的单元测试类
 */

@RunWith(SpringRunner.class) //测试运行器,并加载Spring Boot测试注解
@SpringBootTest //标记单元测试类,并加载项目的上下文环境ApplicationContext
class Edu02CreateMySpringBootProjectApplicationTests {
    //自动创建的单元测试方法示例
    @Test
    void contextLoads() {
    }

    @Autowired //引入HelloController实例对象
    private HelloController helloController;
    @Test
    public void helloControllerTest(){ //新增的单元测试方法
        String hello = helloController.hello();//调用HelloController类中对应的请求控制方法hello()
        System.out.println(hello);//打印输出结果
    }


}

运行测试 鼠标放在 helloControllerTest() 上右击运行

image.png

image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萌狼蓝天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值