springboot使用@SpringBootTest注解进行单元测试-创新互联

一、示例 1.1 添加依赖
4.0.0org.examplespringboot-rabbitmq-fanout-producer1.0-SNAPSHOT88 org.springframework.boot spring-boot-dependencies 2.3.2.RELEASE pom importorg.springframework.bootspring-boot-starter-weborg.springframework.bootspring-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.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


网站栏目:springboot使用@SpringBootTest注解进行单元测试-创新互联
本文URL:http://pwwzsj.com/article/dhiijg.html