栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

springboot使用@SpringBootTest注解进行单元测试

springboot使用@SpringBootTest注解进行单元测试

一、示例 1.1 添加依赖


    4.0.0

    org.example
    springboot-rabbitmq-fanout-producer
    1.0-SNAPSHOT

    
        8
        8
    

    
        
            
                org.springframework.boot
                spring-boot-dependencies
                2.3.2.RELEASE
                pom
                import
            
        
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-test
        
    


可见,我们的单元测试注解是来源spring-boot-starter-test这个依赖的。

1.2 application.yml
# 服务端口
server:
  port: 8080
1.3 主启动
package com;

import javafx.application.Application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FanoutProducer {

    public static void main(String[] args) {
        SpringApplication.run(FanoutProducer.class, args);
    }
}

1.4 业务类
package com.service;

@Component
public class OrderService {
 
     public void makeOrder() {
       System.out.println("测试成功!");
    }
}

1.5 单元测试类
package com.test;

import com.service.OrderService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class FanoutProducerApplicationTests {

    @Autowired
    OrderService orderService;

    @Test
    public void contextLoads() throws Exception {
        orderService.makeOrder();
    }
}

Springboot的@RunWith(SpringRunner.class)注解的意义在于Test测试类要使用注入的类,比如@Autowired注入的类,有了@RunWith(SpringRunner.class)这些类才能实例化到spring容器中,自动注入才能生效,不然直接一个NullPointerExecption。
当然,你也许会看见有些人使用时,没有加上也可以正常使用,具体原因未知,可能是引用的依赖版本问题,视情况而定就行。

1.6 项目结构


关注画了圈的即可。

二、版本说明

首先针对SpringBoot的测试类,2.2版本之前和2.2版本之后是不一样的,在2.2版本之前需要贴注解@SpringBootTest和@RunWith(SpringRunner.class)需要在Spring容器环境下进行测试,因为@Test导包的是org.junit.Test,而 在2.2版本之后只需要贴注解@SpringBootTest,@Test导包为org.junit.jupiter.api.Test

三、重要事项

创建的测试类必须在主启动类所在包路径同级下或其子级下,否则无法扫描到bean,且无法注入需要的bean,会报错

正确示例目录结构:


错误示例:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/698323.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号