JUnit – the unit test of the spring boot actuator endpoint is invalid when the port is specified

Recently, I changed my spring boot attribute to define a management port

I wrote a unit test for the test / metrics endpoint, as follows:

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

It was a thing of the past After adding:

management.port=9001

Test start failed:

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

I tried to change the @ springboottest annotation in the following way:

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

server. Where is the number used by port There seems to be no difference

Then, the management. In the properties file Change the port value to the same as server Port is the same The results are the same

The only way to make the test work is to delete management. Net from the properties file port.

Any suggestions / ideas?

thank you

Solution

Would you like to try adding the following comments to the test class?

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

Check the following link for reference.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>