source

포트를 지정할 때 스프링 부트 액추에이터 끝점의 장치 테스트가 작동하지 않음

factcode 2023. 7. 13. 21:09
반응형

포트를 지정할 때 스프링 부트 액추에이터 끝점의 장치 테스트가 작동하지 않음

최근에 관리 포트를 정의하기 위해 스프링 부트 속성을 변경했습니다.그렇게 함으로써, 제 유닛 테스트는 실패하기 시작했습니다 :(

/metrics 끝점을 테스트하는 단위 테스트를 다음과 같이 작성했습니다.

@RunWith (SpringRunner.class)
@DirtiesContext
@SpringBootTest
public class MetricsTest {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mvc;

    /**
     * Called before each test.
     */
    @Before
    public void setUp() {
        this.context.getBean(MetricsEndpoint.class).setEnabled(true);
        this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
    }

    /**
     * Test for home page.
     *
     * @throws Exception On failure.
     */
    @Test
    public void home()
            throws Exception {
        this.mvc.perform(MockMvcRequestBuilders.get("/metrics"))
                .andExpect(MockMvcResultMatchers.status().isOk());
    }
}        

이전에는 이것이 지나가고 있었습니다.추가 후:

management.port=9001

테스트가 실패하기 시작한 원인은 다음과 같습니다.

home Failed: java.lang.AssertionError: Status expected: <200> but was: <404>

@SpringBoot를 변경해 보았습니다.다음을 사용하여 주석 테스트:

@SpringBootTest (properties = {"management.port=<server.port>"})

여기서 은 server.port에 사용되는 번호입니다.이것은 아무런 차이가 없는 것처럼 보였습니다.

그런 다음 속성 파일의 management.port 값을 server.port와 동일하게 변경했습니다.같은 결과.

테스트를 실행하는 유일한 방법은 속성 파일에서 management.port를 제거하는 것입니다.

제안/생각이 있습니까?

감사해요.

Spring Boot 2.x의 경우 통합 테스트 구성을 간소화할 수 있습니다.

를 들어 사용자 정의 예를 순단 용자 의정 ▁forheartbeat 관리

@Component
@Endpoint(id = "heartbeat")
public class HeartbeatEndpoint {

    @ReadOperation
    public String heartbeat() {
        return "";
    }
}

이 끝점에 대한 통합 테스트 위치

@SpringBootTest(
        classes = HeartbeatEndpointTest.Config.class,
        properties = {
                "management.endpoint.heartbeat.enabled=true",
                "management.endpoints.web.exposure.include=heartbeat"
        })
@AutoConfigureMockMvc
@EnableAutoConfiguration
class HeartbeatEndpointTest {

    private static final String ENDPOINT_PATH = "/actuator/heartbeat";

    @Autowired
    private MockMvc mockMvc;

    @Test
    void testHeartbeat() throws Exception {
        mockMvc
                .perform(get(ENDPOINT_PATH))
                .andExpect(status().isOk())
                .andExpect(content().string(""));
    }

    @Configuration
    @Import(ProcessorTestConfig.class)
    static class Config {

        @Bean
        public HeartbeatEndpoint heartbeatEndpoint() {
            return new HeartbeatEndpoint();
        }

    }

}    

Spring boot test의 경우 연결해야 할 포트를 지정해야 합니다.

기적으다연다니결됩에 됩니다.server.port작동기의 경우가 다를 수 있습니다.

이 작업은 다음과 같이 수행할 수 있습니다.

@SpringBootTest(properties = "server.port=8090")

application.properties는 관리 와 같이 지정합니다.

...
management.server.port=8090
...

다음 주석을 테스트 클래스에 추가해 보셨습니까?

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

다음 링크를 참조하십시오.

숙박업소 이름에 오류가 있지 않습니까?그럴 일은 없습니다.@TestPropertySource(properties = {"management.server.port=..."})@TestPropertySource(properties = {"management.port=.."})

가이드에 따르면 @AutoConfigureMetrics를 사용하면 이를 달성할 수 있습니다.그리고 저는 이것으로 움직였습니다.

클래스 경로에 관계없이 @SpringBootTest를 사용할 때 인메모리 백업을 제외한 미터기 레지스트리는 자동으로 구성되지 않습니다.통합 테스트의 일부로 메트릭을 다른 백엔드로 내보내야 하는 경우 @AutoConfigureMetrics로 주석을 달아야 합니다.

https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing.spring-boot-applications.metrics

동일한 문제가 발생한 경우 application-test.properties에 이를 추가하여 management.port를 null로 만들기만 하면 됩니다(빈 값으로 설정).

management.port=

클래스에 다음과 같은 주석을 달아서 JUNIT에서 테스트 프로파일을 사용해야 합니다.

@ActiveProfiles("test")

사용해 보십시오.

@SpringBootTest(properties = {"management.port="})

@SpringBootTest주석의 우선 순위가 응용 프로그램 속성의 우선 순위보다 높습니다. "management.port=""설정을 해제"합니다.management.port소유물.
이렇게 하면 테스트에서 포트를 구성할 걱정이 없습니다.

저는 같은 문제에 직면했고 여러 가지를 시도했지만 이것이 제가 변화를 주지 않고 제 문제를 해결할 수 있었던 방법입니다.application.yaml

샘플 액추에이터 끝점

@Component
@RestControllerEndpoint(id = "endpoint")
public class SampleEndpoint
{
    @GetMapping
    public String sampleEndpoint(){
      return ""
    }
}

유닛 테스트 케이스

@RunWith(SpringRunner.class)
@SpringBootTest(
    classes = {SampleEndpointTest.Config.class},
    properties = {"management.server.port="}
)
@AutoConfigureMockMvc
public class SampleEndpointTest
{
    @Autowired
    private MockMvc mockMvc;

    @SpringBootApplication(scanBasePackageClasses = {SampleEndpoint.class})
    public static class Config
    {
    }

    @Test
    public void testSampleEndpoint() throws Exception
    {

        mockMvc.perform(
            MockMvcRequestBuilders.get("/actuator/enpoint").accept(APPLICATION_JSON)
        ).andExpect(status().isOk());
    }

이제 정보 끝점을 수동으로 활성화해야 하므로 SpringBoot를 확인하십시오.테스트 태그는 다음과 같은 속성에 이를 포함합니다.

@SpringBootTest(
        properties = {
                "management.info.env.enabled=true" ,
                "management.endpoints.web.exposure.include=info, health"
        })

저는 최근에 이런 문제를 겪었고, 위의 답변들 중 어떤 것도 저에게 말이 되지 않았기 때문에, 저는 조금 더 읽기로 결정했습니다.저의 경우, 저는 이미 두 가지를 정의했습니다.server.port그리고.management.server.port~하듯이8091내가 보기에는application-test.yaml파일, 그리고 왜 내 시험이 a를 받는지 이해할 수 없었습니다.connection refused오류 메시지입니다.

주석을 사용하는 대신에@SpringBootTest()사용해야 했습니다.@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)이로 인해 yaml 파일의 포트 번호가 사용됩니다.이에 대해서는 설명서에서 간략히 설명합니다.관련 섹션 인용:

DEFINED_PORT — Embedded Web Application Context를 로드하고 실제 서블릿 환경을 제공합니다.포함된 서블릿 컨테이너는 정의된 포트(예: application.properties 또는 기본 포트 8080)에서 시작되고 수신됩니다.

에 있는 것 같습니다.SpringBootTest기본값은 실제 서블릿 환경을 시작하지 않는 것이며, 그렇지 않은 경우WebEnvironment그러면 명시적으로 지정됩니다.SpringBootTest.WebEnvironment.MOCK는 기본값으로 사용됩니다.

장시간 검색 후:Springboot라는 멋진 주석이 있습니다.@LocalManagementPort!

와 유사하게 작동합니다.@LocalServerPort하지만 작동기 엔드포인트의 경우.

구성 예는 다음과 같습니다.

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MetricsIT {

    @Autowired
    RestTemplateBuilder restTemplateBuilder;

    @LocalManagementPort
    int managementPort;

    @Test
    public void testMetrics(){
        ResponseEntity<String> response = restTemplateBuilder
            .rootUri("http://localhost:" + managementPort + "/actuator")
            .build().exchange("/metrics", HttpMethod.GET, new HttpEntity<>(null), String.class);
    }
}

언급URL : https://stackoverflow.com/questions/38505434/unit-testing-of-spring-boot-actuator-endpoints-not-working-when-specifying-a-por

반응형