SpringBoot整合junit

谁践踏了优雅 2024-03-24 16:11 188阅读 0赞

3,SpringBoot整合junit

回顾 Spring 整合 junit

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(classes = SpringConfig.class)
  3. public class UserServiceTest {
  4. @Autowired
  5. private BookService bookService;
  6. @Test
  7. public void testSave(){
  8. bookService.save();
  9. }
  10. }

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

  • 在测试类上添加 SpringBootTest 注解
  • 使用 @Autowired 注入要测试的资源
  • 定义测试方法进行测试

3.1 环境准备

创建一个名为 springboot_07_testSpringBoot 工程,工程目录结构如下

3022b7566e48496aaab67713090872c3.png

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

  1. public interface BookService {
  2. public void save();
  3. }

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

  1. @Service
  2. public class BookServiceImpl implements BookService {
  3. @Override
  4. public void save() {
  5. System.out.println("book service is running ...");
  6. }
  7. }

3.2 编写测试类

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

  1. @SpringBootTest
  2. class Springboot07TestApplicationTests {
  3. @Autowired
  4. private BookService bookService;
  5. @Test
  6. public void save() {
  7. bookService.save();
  8. }
  9. }

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

例如:

  • 引导类所在包是 com.itheima
  • 测试类所在包是 com.itheima

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

发表评论

表情:
评论列表 (有 0 条评论,188人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringBoot整合Junit

    和整合Mybatis一样分几个步骤 1. 添加Junit的起步依赖 2. 编写测试类 3. 控制台打印信息 总的来说这个还是很简单的 添加Junit的起步依赖