簡體   English   中英

Spring 引導執行器端點的單元測試在指定端口時不起作用

[英]Unit testing of Spring Boot Actuator endpoints not working when specifying a port

最近我更改了我的 spring 引導屬性以定義管理端口。 這樣做,我的單元測試開始失敗:(

我編寫了一個單元測試來測試/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>

我嘗試使用以下方法更改 @SpringBootTest 注釋:

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

server.port 使用的數字在哪里。 這似乎沒有任何區別。

然后將屬性文件中的 management.port 值更改為與 server.port 相同。 結果相同。

使測試工作的唯一方法是從屬性文件中刪除 management.port。

有什么建議/想法嗎?

謝謝

您是否嘗試將以下注釋添加到您的測試類中?

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

檢查以下鏈接以供參考

對於 Spring 啟動測試,我們需要指定它需要連接的端口。

默認情況下,它連接到server.port ,在執行器的情況下是不同的。

這可以通過

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

application.properties我們指定管理端口如下

...
management.port=8090
...

屬性名稱沒有錯誤嗎? 不應該是@TestPropertySource(properties = {"management.server.port=..."})而不是@TestPropertySource(properties = {"management.port=.."})

對於 Spring Boot 2.x,可以簡化集成測試配置。

例如簡單的自定義heartbeat端點

@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();
        }

    }

}    

有同樣的問題,你只需要通過在 application-test.properties 中添加它來使 management.port 為空(將其設置為空值)

management.port=

確保您在 JUnit 中使用測試配置文件

@ActiveProfiles("test")

該指南指出,這可以通過@AutoConfigureMetrics 實現。 我為此而感動。

無論您的類路徑如何,在使用 @SpringBootTest 時,除內存支持外的儀表注冊表都不會自動配置。 如果您需要將指標作為集成測試的一部分導出到不同的后端,請使用 @AutoConfigureMetrics 對其進行注釋。

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

嘗試使用

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

@SpringBootTest注釋中定義的屬性比應用程序屬性中的屬性具有更高的優先級 "management.port="將“取消設置” management.port屬性。
這樣您就不必擔心在測試中配置端口。

我面臨同樣的問題並嘗試了幾件事,但這就是我能夠在不更改application.yaml情況下解決我的問題的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());
    }

由於現在必須手動啟用 info 端點,確保 SpringBootTest 標簽在屬性中包含它,如下所示:

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

我最近遇到了這個問題,由於上述答案對我沒有任何意義,我決定多讀一點。 就我而言,我已經在我的測試application-test.yaml文件中將server.portmanagement.server.port都定義為8091 ,並且無法理解為什么我的測試收到connection refused錯誤消息。

事實證明,我需要使用@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)而不是使用注釋@SpringBootTest() ) - 這會導致使用 yaml 文件中的端口號。 手冊中對此進行了簡要討論。 引用相關部分:

DEFINED_PORT — 加載 EmbeddedWebApplicationContext 並提供真實的 servlet 環境。 嵌入式 servlet 容器啟動並在定義的端口上偵聽(即從您的 application.properties 或默認端口 8080)。

SpringBootTest中似乎默認是避免啟動真正的 servlet 環境,如果沒有明確指定WebEnvironment ,則SpringBootTest.WebEnvironment.MOCK用作默認值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM