Java开发学习(三十八)----SpringBoot整合junit

先来回顾下 Spring 整合 junit

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {
    
    @Autowired
    private BookService bookService;
    
    @Test
    public void testSave(){
        bookService.save();
    }
}

使用 @RunWith 注解指定运行器,使用 @ContextConfiguration 注解来指定配置类或者配置文件。而 SpringBoot 整合 junit 特别简单,分为以下三步完成

  • 在测试类上添加 SpringBootTest 注解

  • 使用 @Autowired 注入要测试的资源

  • 定义测试方法进行测试

一、环境准备

创建一个名为 springboot_07_testSpringBoot 工程,,参考Java开发学习(三十五)----SpringBoot快速入门及起步依赖解析,工程目录结构如下

com.itheima.service 下创建 BookService 接口,内容如下

public interface BookService {
    public void save();
}

com.itheima.service.impl 包写创建一个 BookServiceImpl 类,使其实现 BookService 接口,内容如下

@Service
public class BookServiceImpl implements BookService {
    @Override
    public void save() {
        System.out.println("book service is running ...");
    }
}

二、编写测试类

test/java 下创建 com.itheima 包,在该包下创建测试类,将 BookService 注入到该测试类中

@SpringBootTest
class Springboot07TestApplicationTests {
​
    @Autowired
    private BookService bookService;
​
    @Test
    public void save() {
        bookService.save();
    }
}

注意:这里的引导类所在包必须是测试类所在包及其子包。

例如:

  • 引导类所在包是 com.itheima

  • 测试类所在包是 com.itheima

如果不满足这个要求的话,就需要在使用 @SpringBootTest 注解时,使用 classes 属性指定引导类的字节码对象。如 @SpringBootTest(classes = Springboot07TestApplication.class)

 



如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
posted @   |旧市拾荒|  阅读(119)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2019-10-18 TensorFlow的数据读取机制
点击右上角即可分享
微信分享提示