springboot集成测试-小例子

Spring Boot 集成测试 (一)测试一般程序 1.1测试步骤 在pom.xml 中加入测试环境的依赖。 在测试类上加入@RunWith(SpringRunner.class) 与@SpringBootTest 注解。 1.2简单测试例子 在pom.xml 中引入相关依赖 <dependency> <groupId>org.springframework.boot<... 阅读详情

环境

MacBook Pro
idea:2019.1
Java:1.8
springboot:2.1.4

前言

最近在看springboot实战,看到第四章节测试Web应用测试->模拟springMVC时,跟着书中走,总是出问题;这里记录下:

@RunWith(SpringJUnit4ClassRunner.class)
 @SpringApplicationConfiguration(
      classes = ReadingListApplication.class)
@WebAppConfiguration
public class MockMvcWebTests {
...

上面是书中的写法, 但是在我的环境中,会报错;
①因为@SpringApplicationConfiguration在springboot1.5+时,已经去掉了,应该使用@SpringbootTest;
②@WebAppConfiguration我把它替换成@AutoConfigureMockMvc,因为不换总是报错。

分析

一开始我改成如下:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ReadingListController.class)
@WebAppConfiguration
public class MockMvcWebTests {
...

会报错:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'readingListController': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.misssad.springbootdemo.repository.ReadingListRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

这个错是说,需要无参构造器,无法创建bean
但是 代码里就是构造器注入,就是要用那个有参构造器的;不能无参,况且,无参依然报错。

和

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.misssad.springbootdemo.repository.ReadingListRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

这个错是说,上下文里面没有ReadingListRepository这个bean
因为ReadingListController类里面依赖了ReadingListRepository,但是视乎这个模拟器只只加载了ReadingListController,它的依赖bean没有加载;

接着我改为:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ReadingListController.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@WebAppConfiguration
public class MockMvcWebTests {
...

错误变为:

java.lang.IllegalStateException: @WebAppConfiguration should only be used with @SpringBootTest when @SpringBootTest is configured with a mock web environment. Please remove @WebAppConfiguration or reconfigure @SpringBootTest

这段是我没有看懂的,其大概的意思:

当@SpringBootTest配置了模拟Web环境时,@ WebAppConfiguration只能与@SpringBootTest一起使用。
请删除@WebAppConfiguration或重新配置@SpringBootTest

明明就是web环境啊,为什么会报这个错,目前没有搞懂???

接着我又改为如下:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ReadingListController.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class MockMvcWebTests {
...

报了个这样的错误:

Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

也就是Servlet这个容器bean,它没有找到。

最后我把@SpringBootTest中的classes参数去掉就行了,也就是最终代码;

最终代码

所以最终代码就变成了;(相关代码我就不贴了,都是参考springboot实战.pdf那边书的)

import com.misssad.springbootdemo.controller.ReadingListController;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class MockMvcWebTests {

    @Autowired
    private WebApplicationContext webContext;

    private MockMvc mockMvc;

    /*产生一个MockMvc实例
    有了这个实例,就可以写测试用例了
     */
    @Before
    public void setupMockMvc(){
        mockMvc = MockMvcBuilders.webAppContextSetup(webContext)
                .build();
        System.out.println("-------运行成功------");
    }

    /*①向readingList发起一个get请求;
    * ②希望该请求处理成功(isOK()会判断HTTP200响应码);
    * ③视图的逻辑名称为readingList;
    * ④判断模型包含一个名为books的属性
    * ⑤该属性是个空集合
    */
    @Test
    public void homePage() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/readingList"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.view().name("readList"))
                .andExpect(MockMvcResultMatchers.model().attributeExists("books"))
                .andExpect(MockMvcResultMatchers.model()
                        .attribute("books", Matchers.is(Matchers.empty())));
    }


}

参考地址:

https://stackoverflow.com/a/42788074
Spring Boot 集成测试

Spring Boot 单元测试和集成测试实现详解 主要介绍了Spring Boot 单元测试和集成测试实现详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 立即下载

相关推荐

工业安全生产 AI 视频分析与隐患识别平台技术方案

工业安全生产 AI 视频分析与隐患识别平台技术方案2026 年是我国安全生产专项整治三年行动巩固提升的收官之年,也是 "十四五" 安全生产规划全面落地的关键节点。国家应急管理部最新发布的《"工业互联网 + 安全生产" 行动计划(2026-2028 年)》明确提出,到 2028 年底,全国规模以上工业企业安全生产数字化覆盖率要达到 95% 以上,高危行业企业要 100% 建成智能化安全监测预警系统。国务院安委会印发的《关于进一步加强安全生产隐患排查治理体系建设的指导意见》要求,所有化工、矿山、建筑施工等高危行

随读手记 457

深入解析java.lang.IllegalStateException异常

是Java中的一个非受检异常,它表示在不适当的时间或状态下调用方法。日志记录工具:如Log4j、Logback等,可以记录异常信息和错误日志,方便排查和分析问题。断言工具:如Assert类,可以在程序中添加断言语句,用于验证代码中的假设条件是否满足,帮助我们在开发和测试阶段快速发现问题。异常处理框架:如Spring框架中的异常处理机制,可以统一处理应用程序中的异常,提供统一的异常处理逻辑和错误信息返回。异常是程序中常见的错误和异常情况,合理处理异常对于保证程序的正确性和稳定性非常重要。

博客 4万+

保姆级教程:在ESXi 8.0上为NVIDIA ConnectX-5/6网卡开启SR-IOV(从BIOS到虚拟机配置)

本文提供在ESXi 8.0上为NVIDIA ConnectX-5/6网卡开启SR-IOV的详细教程,涵盖BIOS设置、固件配置、驱动优化及虚拟机部署。通过SR-IOV技术,显著提升虚拟化环境中的网络性能,适用于高性能计算、AI训练等场景。

weixin_26934905的博客 472

【测试】Webflux的Junit单元测试

本年度公司框架将加入WebFlux作为Reactive交互技术(传统模式还会保留)。WebFlux是基于Netty,在交互上采用的是异步处理模式,这次加入Webflux是希望增强框架的交互多样性和容载能力。 Webflux的具体实现将不在这里细说,本次主要讲解一下通过Junit调用Webflux遇到的“坑”。 spring-boot-starter-webflux 和 spring-boot-starter-web 同时引入不生效的问题。 通过官网的说明不难发现 旧版Web包使用的是阻塞结构,而Webfl

Kida 的躺平小屋 1616

Rocky Linux 9 远程桌面配置全攻略:从零搭建XRDP服务(含防火墙设置)

本文提供了在Rocky Linux 9上从零开始配置XRDP远程桌面服务的完整指南。详细介绍了系统准备、XRDP服务安装、防火墙与SELinux安全设置、多用户性能优化以及多平台客户端连接实测。重点解决了使用Windows远程桌面协议(RDP)连接Rocky Linux时常见的配置难点与安全问题,帮助用户获得稳定高效的图形化远程访问体验。

vodka的博客 662

从仿真到器件:铌酸锂电光调制器Comsol建模避坑指南

本文详细介绍了铌酸锂电光调制器在Comsol中的建模全流程,涵盖晶体切向选择、材料参数配置、多物理场耦合等关键技术。通过实战案例和调试技巧,帮助工程师避开常见建模陷阱,提升仿真精度与效率,特别适用于高速光通信系统的器件设计与优化。

m2n3b4v5c6的博客 427

JUint4测试报错 No thread-bound request found: Are you referring to

听取了论坛老哥的建议:把所有测试功能都自动化起来。所以现在接着练习JUnit4。 今天测试登录功能,核心代码如下: @Autowired UserMapper userMapper; @Autowired HttpServletRequest request; /** * 用户登录操作。将用户存入session * * ...

过道 4010

[Python图像处理] 十.形态学之图像顶帽运算和黑帽运算

数学形态学(Mathematical morphology)是一门建立在格论和拓扑学基础之上的图像分析学科,是数学形态学图像处理的基本理论。其基本的运算包括:腐蚀和膨胀、开运算和闭运算、骨架抽取、极限腐蚀、击中击不中变换、形态学梯度、Top-hat变换、颗粒分析、流域变换等。本篇文章主要讲解Python调用OpenCV实现图像形态学转化,包括图像顶帽运算和图像黑帽运算,基础性知识希望对您有所帮助。

杨秀璋的专栏 1万+

什么是集成测试(集成测试示例教程)

集成测试是为了在集成时测试模块/组件,以验证它们是否按预期工作,即测试单独工作的模块在集成时没有问题。 在使用黑盒测试技术测试大型应用程序时,涉及多个彼此紧密耦合的模块的组合。我们可以应用集成测试技术概念来测试这些类型的场景。 什么是集成测试? 集成测试的含义非常简单- 将单元测试模块逐个集成...

chengyuweng7838的博客 8万+

基于微博API与Scrapy-Redis的城市情绪地图数据爬取实战

本文详细介绍了如何利用Python爬虫技术从微博平台获取用户发布内容,用于构建城市情绪地图的毕业设计项目。文章涵盖了微博API的调用、Scrapy-Redis分布式爬虫架构、数据清洗与存储、反爬虫策略应对以及情绪分析预处理等关键技术,提供了完整的代码实现和实战经验。python复制下载# items.py"""清洗文本数据"""if text:# 移除HTML标签# 移除多余空白字符"""解析微博日期格式"""

2201_76125261的博客 451

【C#程序员入门AI】AI应用的操作系统:Semantic Kernel 2026实战

用户ID用户信息

人工智能AI技术 1252

解决:java.lang.IllegalStateException: Either 'name' or 'value' must be provided in @FeignClient(很有用)

java.lang.IllegalStateException: Either 'name' or 'value' must be provided in @FeignClient at org.springframework.cloud.openfeign.FeignClientsRegistrar.getClientName(FeignClientsRegistrar.java:346) ~...

Jav 8838

USB驱动(URB)

本文介绍了Linux内核中USB驱动开发的核心概念URB(USB Request Block)。URB是主机与USB设备间传输数据的抽象结构体,包含目标设备、端点信息、数据缓冲区等关键字段。文章详细解析了URB的生命周期(分配、填充、提交、回调、释放)、四种传输类型(控制、批量、中断、等时)及其应用场景,并提供了鼠标设备的中断传输示例代码。最后强调了URB使用注意事项,包括DMA缓冲区分配、错误处理和资源释放等。URB作为USB驱动与内核通信的桥梁,是构建稳定USB驱动程序的基础。

m0_49476241的博客 924

Springboot 测试类demo

package test; import java.net.URL; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBo

u012639897的博客 361

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

小架构step系列14:白盒集成测试原理

这里的白盒测试是指开发编写测试代码来进行测试,集成测试是指从Controller开始对http接口调用的整个流程进行测试。这个流程就是对一个http请求的响应流程,正常运行的时候是通过springboot内嵌的tomcat来启动一个web server来监听http请求,然后响应该http请求。在测试的时候,如果也需要启动一个web server来监听请求,那么测试就更加困难了一些。还好spring-test为这个场景提供了便利,本文来了解一下它们的原理。

swingline的专栏 375

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

springboot junit 测试示例

@RunWith(SpringRunner.class) @SpringBootTest(classes = WebSpringApplication.class) //@ContextConfiguration(locations={"classpath:applicationContext.xml"}) //加载配置文件 public class XProductTest { @Re

愿见世间如清水 791

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

SpringBoot单元测试

package com.wangh.test;import javax.annotation.Resource;import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; impo

椭圆的博客 280

企业分布式微服务云SpringCloud SpringBoot mybatis (十八)springboot在启动时注入了哪些bean...

在程序入口加入: @SpringBootApplication public class SpringbootFirstApplication { public static void main(String[] args) { SpringApplication.run(SpringbootFirstApplication.class, args...

aidgb04622的专栏 96

springboot 单元测试test

pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> 一旦依赖了spring-boot-starter-test,下面这些类库将被一同依赖进去: J

somdip的博客 1042

springboot 测试类

import org.junit.runner.RunWith;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;@Runwith(SpringRunner.class) @SpringBootTest(cl...

weixin_34329187的博客 85

【SpringBoot】单元测试

@RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)public class TestUserController { @Autowired private TestRest

哈哈哈哈哈哈哈 397

SpringBoot Junit单元测试

Junit单元测试 import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.ContextConfiguration; im

爱吃鱼油 2466

SpringBootTest

Springboot Test package com.example.demo; import com.example.demo.service.XXX; import org.junit.Test; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.runner.RunWith; import org.springframework.beans.factor

qq_39296049的博客 264

SpringBoot以及SPringCLoud工程单元测试案例,需要导入一些包,单元测试模板Java代码

@Slf4j @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class) public class TestDaoTest { @Autowired private AiHandleDupDao aiHandleDupDao; @Autowired private Ai...

java技术专家全栈成长之路 1095
上一篇: Macbook IDEA快捷键及相应的修改
下一篇: java8基本概念
山鬼谣me
博客等级 码龄13年 543粉丝 504原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山鬼谣me

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值