首页 > 解决方案 > Spring Boot MockMvc 测试在使用“management.server.port”属性而不是已弃用的“management.port”时为执行器端点提供 404

问题描述

我之前在应用程序 yaml 中使用 management.port 作为管理端点端口。但是,将其更改为在以下应用程序 yaml 文件中使用。它一直未能通过我对健康端点的执行器测试。当我运行应用程序时,端点正常工作。

应用程序.yaml

spring:
  profiles.active: development

management:
  endpoints:
    web:
      exposure:
        include: "*"
  server:
    port: 9000

server:
  port: 8000
---
spring:
  profiles: development

logging:
  level:
    root: INFO
    org.springframework.web: INFO

---
spring:
  profiles: staging

logging:
  level:
    root: ERROR
    org.springframework.web: ERROR

集成测试类

package com.rps;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import com.rps.infrastructure.repository.PlayersInMemoryRepository;
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.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

/**
 * Integration testing the actual API Check the guide here: https://spring.io/guides/gs/testing-web/
 */
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class RPSApplicationIT {

  @Autowired
  private WebApplicationContext context;

  @Autowired
  private PlayersInMemoryRepository playersInMemoryRepository;

  private MockMvc mockMvc;

  @Before
  public void setupMockMvc() {
    mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
  }

  @Test
  public void shouldReturnActuatorHealthResponse() throws Exception {
    this.mockMvc.perform(get("/actuator/health"))
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(content().json("{\"status\":\"UP\"}"));
  }

}

标签: javaspring-bootjunit

解决方案


我认为问题是由于应用程序和执行器的不同端口而出现的。

将其更改为 0 应该可以解决您的测试问题:

@TestPropertySource(properties = { "management.server.port=0" })

编辑- 我找到了一个相关的帖子,也许你可以查看那里提出的其他解决方案(即使没有接受的答案):指定端口时 Spring Boot Actuator 端点的单元测试不起作用


推荐阅读