recently I changed my spring boot properties to define a management port. In doing so, my unit tests started to fail :(
I wrote a unit test that tested the /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());
}
}
Previously this was passing. After adding:
management.port=9001
The tests started failing with:
home Failed: java.lang.AssertionError: Status expected: <200> but was: <404>
I tried changing the @SpringBootTest annotation with:
@SpringBootTest (properties = {"management.port=<server.port>"})
Where is the number used for the server.port. This didn't seem to make any difference.
So then changed the management.port value in the property file to be the same as the server.port. Same result.
The only way to get the test to work is remove the management.port from the property file.
Any suggestions/thoughts ?
Thanks
Did you try adding the following annotation to your test class?
@TestPropertySource(properties = {"management.port=0"})