spring - 在不启动完整应用程序的情况下测试 Spring Boot Actuator 端点
问题描述
我的 Spring Boot 应用程序配置了一个数据源,并公开了 Spring Actuator 运行状况和 prometheus 指标。
应用程序.yml
spring:
datasource:
driver-class-name: org.mariadb.jdbc.Driver
username: ${db.username}
password: ${db.password}
url: jdbc:mariadb://${db.host}:${db.port}/${db.schema}
management:
endpoints:
web:
exposure:
include: 'health, prometheus'
启动应用程序时,/actuator/prometheus
提供包含指标的响应。现在我想为prometheus
端点编写一个非常基本的测试(JUnit 5)。这是它目前的样子:
测试班
@SpringBootTest
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
public class HealthMetricsIT {
@Autowired
private MockMvc mockMvc;
@Test
public void shouldProvideHealthMetric() throws Exception {
mockMvc.perform(get("/actuator/prometheus")).andExpect(status().isOk());
}
}
但是我在这里遇到了两个问题,我还不知道如何解决它们。
第一期
- 使用此设置,测试似乎会启动整个应用程序,从而尝试连接到正在运行的数据库。
- 测试将无法正常启动,因为
db
未提供前缀为的数据源属性。
如何在不启动数据库连接的情况下开始此测试?
第 2 期
即使我的本地数据库正在运行并且我提供了所有db
属性,测试也会失败。这次是因为我得到的是 HTTP 404 而不是 200。
解决方案
至于MockMvc
测试 Spring MVC 组件(你的@Controller
和@RestController
),我猜你得到的自动配置的模拟 Servlet 环境@AutoConfigureMockMvc
不会包含任何 Actuator 端点。
相反,您可以编写一个不使用MockMvc
而是启动嵌入式 Servlet 容器的集成测试。
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
// @ExtendWith(SpringExtension.class) can be omitted with recent Spring Boot versions
public class HealthMetricsIT {
@Autowired
private WebTestClient webTestClient; // or TestRestTemplate
@Test
public void shouldProvideHealthMetric() throws Exception {
webTestClient
.get()
.uri("/actuator/health")
.exchange()
.expectStatus().isOk();
}
}
对于此测试,您必须确保应用程序启动时所需的所有基础架构组件(数据库等)都可用。
使用 Testcontainers,您几乎可以毫不费力地为集成测试提供数据库。
推荐阅读
- java - com.sun.mail.util.MailConnectException:无法连接到主机,端口:smtp.gmail.com,587 超时 -1
- google-apps-script - 将错误消息设置为英语
- design-patterns - 如何在字符串中找到转义字符\?
- java - 逃逸分析是否有助于 JVM 在堆栈上分配数组?
- tornado - 为什么 Tornado 会花时间在 socket.send(data) 中?
- php - chmod():Laravel 中不允许的操作
- emacs - Emacsclient:搜索程序:没有这样的文件或目录,ruby
- parameters - 如何获取视图组件中的参数值?
- android - 来自后台应用程序的 Android 屏幕截图
- javascript - 找不到 Django 静态文件 404