1.说明

Spring Boot进行单元测试,
通过集成spring-boot-starter-test,
同时支持Junit4和Junit5测试框架,
下面使用Junit5进行单元测试,
基于一个已有的Spring Boot服务:SpringBoot开发Restful接口
开发对应Restful接口的方法的单元测试。

区别于Junit4/5对于类级别的单元测试,
通过spring-boot-starter-test测试框架,
能够启动一个完全运行的web服务器,
同时监听自定义或随机端口模拟服务调用请求,
也可以使用Spring各种上下文和Bean实例,
进行服务器级别的单元测试。

2.引入Maven依赖

在pom.xml引入spring-boot-starter-test的依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions>
</dependency>

如果仅使用Junit5,
不需要使用Junit4,
需要排除掉junit-vintage-engine依赖,
否则运行测试用例时可能会报错,
同时也能够避免Junit4和Junit5混用。
junit-vintage-engine是JUnit4的测试引擎。
junit-jupiter-engine是JUnit5的测试引擎。

3.新建测试类

在src/test/java目录下,
新建UserController的测试类UserControllerTest:

/*** 用户的增删改查相关接口单元测试*/
@SpringBootTest
public class UserControllerTest {}

注意在类名上面使用注解@SpringBootTest。
另外对于Junit4,
如果需要测试容器,
除了要加上@SpringBootTest,
还需要加上@RunWith(SpringRunner.class)
或者@RunWith(SpringJUnit4ClassRunner.class),
对于Junit5则不需要@RunWith。

4.新建测试方法

新建测试方法testGetOneUser(),
方法上面使用Junit5提供的注解@Test,
标识这是一个测试方法,
用于测试UserController的getOneUser的功能,
注意使用@Autowired注入UserController的实例,
这样在测试方法中就能调用相应的API,
而不会报空指针异常了。

完整的UserControllerTest.java:

package com.yuwen.spring.demo.controller;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.yuwen.spring.demo.entity.User;@SpringBootTest
public class UserControllerTest {@AutowiredUserController userController;@Testpublic void testGetOneUser() {Long id = 90955L;User oneUser = userController.getOneUser(id);System.out.println(oneUser);}
}

5.运行测试类

在Eclipse中运行测试类,
右键测试类UserControllerTest -> Run As -> Junit Test,
或者使用快捷键:
Alt + Shift + X, T
UserControllerTest单元测试执行结果如下:

17:37:22.939 [main] INFO  [org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:308)] - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.yuwen.spring.demo.controller.UserControllerTest], using SpringBootContextLoader
17:37:22.947 [main] INFO  [org.springframework.test.context.support.AbstractContextLoader.generateDefaultLocations(AbstractContextLoader.java:264)] - Could not detect default resource locations for test class [com.yuwen.spring.demo.controller.UserControllerTest]: no resource found for suffixes {-context.xml, Context.groovy}.
17:37:22.948 [main] INFO  [org.springframework.test.context.support.AnnotationConfigContextLoaderUtils.detectDefaultConfigurationClasses(AnnotationConfigContextLoaderUtils.java:83)] - Could not detect default configuration classes for test class [com.yuwen.spring.demo.controller.UserControllerTest]: UserControllerTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
17:37:23.042 [main] INFO  [org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:237)] - Found @SpringBootConfiguration com.yuwen.spring.demo.DemoApplication for test class com.yuwen.spring.demo.controller.UserControllerTest
17:37:23.125 [main] INFO  [org.springframework.test.context.support.AbstractTestContextBootstrapper.getDefaultTestExecutionListenerClassNames(AbstractTestContextBootstrapper.java:248)] - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
17:37:23.135 [main] INFO  [org.springframework.test.context.support.AbstractTestContextBootstrapper.getTestExecutionListeners(AbstractTestContextBootstrapper.java:177)] - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@11f0a5a1, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@10f7f7de, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@73a8da0f, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@50dfbc58, org.springframework.test.context.support.DirtiesContextTestExecutionListener@4416d64f, org.springframework.test.context.event.EventPublishingTestExecutionListener@6bf08014, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@5e3d57c7, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@732d0d24, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@1fb19a0, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@6ee4d9ab, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@5a5338df, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@418c5a9c].   ____          _            __ _ _/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/  ___)| |_)| | | | | || (_| |  ) ) ) )'  |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot ::        (v2.3.1.RELEASE)17:37:23.465 [main] INFO  [org.springframework.boot.StartupInfoLogger.logStarting(StartupInfoLogger.java:55)] - Starting UserControllerTest on yuwen-asiainfo with PID 17592 (started by yuwen in D:\Code\Learn\test-util\junit\junit5-springboot)
17:37:23.468 [main] INFO  [org.springframework.boot.SpringApplication.logStartupProfileInfo(SpringApplication.java:651)] - No active profile set, falling back to default profiles: default
17:37:24.769 [main] INFO  [org.springframework.scheduling.concurrent.ExecutorConfigurationSupport.initialize(ExecutorConfigurationSupport.java:181)] - Initializing ExecutorService 'applicationTaskExecutor'
17:37:25.147 [main] INFO  [org.springframework.boot.StartupInfoLogger.logStarted(StartupInfoLogger.java:61)] - Started UserControllerTest in 1.977 seconds (JVM running for 3.172)
getOneUser, id=90955
User [id=90955, name=null, birthday=null, email=null]
17:37:25.344 [SpringContextShutdownHook] INFO  [org.springframework.scheduling.concurrent.ExecutorConfigurationSupport.shutdown(ExecutorConfigurationSupport.java:218)] - Shutting down ExecutorService 'applicationTaskExecutor'

可以看到启动了Spring Boot容器,
然后调用了UserController的getOneUser接口。

6.参考文章

Junit5集成到Maven工程JUnit 5 User GuideJunit5 GithubJUnit 5 测试 Spring 引擎的时候提示 junit-vintage 错误springboot常用starter⑬-spring-boot-starter-test


http://www.taodudu.cc/news/show-1250949.html

相关文章:

  • 语言代码表
  • Protobuf生成Java代码(Maven)
  • Protobuf生成Java代码(命令行)
  • Maven查看插件信息
  • SpringBoot脚手架工程快速搭建
  • SpringBoot集成MyBatis-Plus分页插件
  • SNMP客户端工具MIB Browser
  • PowerDesigner运行自定义VBS脚本,复制Name到Comment
  • BitMap-BitSet(JDK1.8)基本使用入门
  • IDEA查看Java类的UML关系图
  • 30. 包含min函数的栈
  • 35. 复杂链表的复制
  • 58 - II. 左旋转字符串
  • 03. 数组中重复的数字
  • 53 - II. 0~n-1中缺失的数字
  • 04. 二维数组中的查找
  • 11. 旋转数组的最小数字
  • 50. 第一个只出现一次的字符
  • 32 - I. 从上到下打印二叉树
  • 32 - II. 从上到下打印二叉树 II
  • 32 - III. 从上到下打印二叉树 III
  • 26. 树的子结构
  • PostgreSQL数据库密码
  • SpringBoot中使用Hibernate Validator校验工具类
  • 28. 对称的二叉树
  • 解决tomcat的undeploy
  • 解决eclipse出现The superclass javax.servlet.http.HttpServlet was not found on the Java Build Path
  • 下载安装neo4j
  • vue-drag-resize实线页面的拖拽与缩放
  • 解决IDEA不能编译XML文件

Junit5集成到SpringBoot工程相关推荐

  1. Junit5集成到Maven工程

    1.说明 Junit5是单元测试框架Juint4的升级版, 与Junit4框架有很大的不同, 它由三个模块组成: JUnit5 = JUnit Platform + JUnit Jupiter + J ...

  2. Redis集成到Maven工程(Jedis客户端)

    1.说明 Redis不仅可以使用命令行操作, 也支持大部分主流编程语言的客户端, 本文介绍Java客户端Jedis的使用, Jedis API提供了完整的Redis命令, 能够和Redis命令行一一对 ...

  3. Junit4集成到Maven工程

    1.说明 Junit是Java中最常用的单元测试框架, 这里介绍的是Junit4, 开源项目地址:Github Junit4 后续会介绍更优秀的框架Junit5. 下面演示Junit4的基本使用方法, ...

  4. Dubbo(十五)springboot工程dubbo整合SpringCloud Hystrix

    本章将编写一个使用SpringBoot工程集成dubbo使用hystrix组件实现服务熔断示例.包含服务提供者工程和服务消费者工程.主要在实现整合springcloud hystrix过程步骤如下: ...

  5. Java项目集成apollo,SpringBoot集成Apollo配置中心

    准备工作 本文假设读者已经在本地部署Apollo配置中心,如还未部署可参考之前的文章 <Docker部署Apollo配置中心> 文章将引导在Docker中运行Apollo配置中心.在开始使 ...

  6. SpringBoot工程接入腾讯云短信服务平台

    由于业务需要,需要使用第三方短信平台,进行验证码的发送.网上的短信服务平台主要由:百度.腾讯.阿里云:采用官方提供的SDK,调用接口即可. 腾讯云短信服务平台和阿里云短信服务平台,一般步骤为:注册-- ...

  7. 亲测简单易懂可用:阿里云OSS入门实战2(集成到SpringBoot项目中存放用户头像)

    亲测简单易懂可用:阿里云OSS入门实战2(集成到SpringBoot项目中存放用户头像) 大噶好,我们继续延续上一章,学习如何使用OSS存放用户头像代码示例; 在application.propert ...

  8. SpringBoot工程构建时pom父文件导入失败(父类启动依赖导入失败)

    报错:org.springframework.boot:spring-boot-starter-parent:pom:2.6.4 failed to transfer from.... 原因:spri ...

  9. uniapp android原生,在uni-app项目中集成Android原生工程

    [TOC] # 在uni-app项目中集成Android原生工程 按照官方的方案,我们如果进行本地打包的话,需要重新创建一个Android原生工程,于是就会导致我们管理多个项目,切来切去的也麻烦. 经 ...

最新文章

  1. Spring管理Strust的Action
  2. python工程师百度百科-国家认证的Python工程师有什么能力要求?
  3. python自定义异常类时、可以继承的类是_Python异常类型及处理、自定义异常类型、断言...
  4. 自定义权限 android,如何在Android中使用自定义权限?
  5. matlab subplot同时显示多幅图像
  6. NYOJ-聪明的kk(dp)
  7. MATLAB计算卷积幂函数,数论小记(示例代码)
  8. 自定义MVC框架之工具类-图像处理类
  9. 【PMP认证考试之个人总结】第 3 章 项目整合管理
  10. 利用ffmpeg提取视频中的声音为MP3格式
  11. 【数论】【不定方程】n元一次不定方程、佩尔方程、毕达哥拉斯定理、费马大定理
  12. 论文笔记:UCTransNet: Rethinking the Skip Connections in U-Net from a Channel-wisePerspective with Transf
  13. 数据结构——哈夫曼树及其应用
  14. ruby on rails validates uniqueness
  15. 半乳糖修饰人血清白蛋白 Gal-HSA,Gal-PEG-HSA,单糖/多糖修饰蛋白等
  16. 西门子1200PLC控制加KPT1200触摸屏,污水处理厂自控项目实例
  17. Kubernetes 之 二进制安装(二) 证书详解
  18. 达内终端端mysql命令_如何从Windows命令行启动MySQL
  19. mana spark有中文吗_玛娜火花Mana Spark单机版下载-玛娜火花Mana Spark游戏下载-k73游戏之家...
  20. 基于Spark的用户行为路径分析的产品化实践

热门文章

  1. [软件测试_LAB1]安装junit和hamcrest及其使用
  2. sublime text 配置
  3. C++类中的访问权限问题---public/protected/private
  4. c++ list sort方法
  5. SQL Server Compact 3.5开发环境说明
  6. 自考--运筹学--计算题总结
  7. axios从入门到源码分析 -http-xhr
  8. JavaScript算法(实例九)整数的置换 / 求s=a+aa+aaa+aaaa+aa...a的值 / 自守数
  9. 使用VS2010+OpenCV2.4.9简单图像水印代码
  10. python执行命令并返回结果集_如何执行python脚本然后将结果存储为Power BI中的pandas数据集?...