简体   繁体   中英

Spring boot's actuator unavailable when set management port

I use Spring boot + Spring Security + Spring Actuator

My JUnit test class:

@RunWith(SpringRunner.class)
@SpringBootTest()
@AutoConfigureMockMvc
public class ActuatorTests {

    @Autowired
    private MockMvc mockMvc;

    @Test
    @WithMockUser(roles={"USER","SUPERUSER"})
    public void getHealth() throws Exception {
        mockMvc.perform(get("/health"))
        .andExpect(status().isOk());
    }

}

is OK, but when I set management.port: 8088 , my test is KO with this message:

[ERROR]   ActuatorTests.getHealth:37 Status expected:<200> but was:<404>

How to set management port in my JUnit test MockMvc or test configuration?

When management.port is different to server.port Spring will create a separate web application context and a dedicated servlet container where it will register all actuators. A default MockMvc routes requests against the main application web context and not the management one. That is what happening in your case - since no actuators are running in the main application web context you get a 404. To test endpoints running in a management context use the following setup:

@RunWith(SpringRunner.class)
@SpringBootTest
public class ManagementContextMvcTest {

    @Autowired
    private ManagementContextResolver resolver;

    private MockMvc mockMvc;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(
                     (WebApplicationContext) resolver.getApplicationContext()).build();
    }

    @Test
    @WithMockUser(roles = { "USER", "SUPERUSER" })
    public void getHealth() throws Exception {
        mockMvc.perform(get("/health"))
           .andExpect(status().isOk());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM