多模块多个端口服务下 SpringBoot 的单元测试

本文介绍了在SpringBoot项目中如何引入依赖进行单元测试,包括使用`spring-boot-starter-test`和JUnit,以及在多模块项目中的测试类组织规则、依赖注入和注意事项,如测试方法无返回值和`@RunWith(SpringRunner.class)`的使用。
摘要由CSDN通过智能技术生成

1、引入依赖

<!-- 测试工具 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  	<artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>junit</groupId>
  	<artifactId>junit</artifactId>
  <scope>test</scope>
</dependency>

2、创建单元测试

import com.yami.shop.leaf.service.SegmentService;
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;
@SpringBootTest
@RunWith(SpringRunner.class)
public class PushShopApplicationTest {

    @Autowired
    private SegmentService segmentService;
    @Test
    public void main() {
        segmentService.getSegmentId("test");
        System.out.println("hello world");
    }
}

在这里插入图片描述

目录结构
在这里插入图片描述
外层父pom 多个模块,多个端口启动项目多个服务

3、注意事项

1、@Test 注解为org.junit.Test包内的
2、多模块项目,测试类要创建在与web一个模块内 (就是有主程序入口XXXApplication的模块,而不是bean,common 这些没有启动类,没有配置端口的模块,那样会找不到启动入口也扫描不到 @Autowired 的类 bean 依赖会注入不了
test 包下面的层级关系需要与 main 下面的层级关系一样
3、测试方法不能有返回值,不能为static
4、引入依赖进来不要单独写版本号容易冲突运行不起来
5、@RunWith(SpringRunner.class) 可以当固定写法
6、

@Test
    public void main() {
        segmentService.getSegmentId("test");
        System.out.println("hello world");
    }

方法必须是public的

  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值