前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >11-SpringBoot整合Junit

11-SpringBoot整合Junit

作者头像
Devops海洋的渔夫
发布2022-03-23 15:47:22
2220
发布2022-03-23 15:47:22
举报
文章被收录于专栏:Devops专栏

11-SpringBoot整合Junit

SpringBoot整合Junit

实现步骤

  • 搭建SpringBoot工程
  • 引入starter-test起步依赖
  • 编写测试类
  • 添加测试相关注解
    • @RunWith(SpringRunner.class)
    • @SpringBootTest(classes = 启动类.class)
  • 编写测试方法

实现案例

1.搭建SpringBoot-test工程

不选择依赖,直接创建。

2. 引入starter-test起步依赖
代码语言:javascript
复制
<dependencies>
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
   </dependency>

   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
   </dependency>
</dependencies>
3. 编写 UserService 类,用于验证依赖注入
代码语言:javascript
复制
package com.lijw.springboottest;

import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    public String findAll(){
        return "findAll";
    }
    
}

“注意:要将 UserService 等类写在 package com.lijw.springboottest 下,如果写到其他包,例如:com.lijw.service ,那么默认 Bean 扫描不到。 ”

4. 编写测试类
代码语言:javascript
复制
package com.lijw.springboottest;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest(classes = SpringbootTestApplication.class)
public class UserServiceTest {

    @Autowired
    UserService userService;

    @Test
    public void testFindAll(){
        System.out.println(userService.findAll());
    }
}
5. 执行测试
6.如果测试类与SpringBoot应用类在同一个package下,可以省略 (classes = SpringbootTestApplication.class)
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-03-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 海洋的渔夫 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 11-SpringBoot整合Junit
    • SpringBoot整合Junit
      • 实现步骤
      • 实现案例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档