本文介绍了设置管理端口时,Spring Boot的执行器不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Spring Boot + Spring Security + Spring Actuator

I use Spring boot + Spring Security + Spring Actuator

我的JUnit测试类:

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

}

可以,但是当我设置management.port: 8088时,此消息的测试结果为KO:

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>

如何在我的JUnit测试MockMvc或测试配置中设置管理端口?

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

推荐答案

management.portserver.port不同时,Spring将创建一个单独的Web应用程序上下文和一个专用的servlet容器,在其中注册所有执行器.默认的MockMvc是针对主要应用程序Web上下文而不是管理上下文路由请求.这就是您的情况-由于在主应用程序Web上下文中没有执行器在运行,因此您会得到404.要测试在管理上下文中运行的端点,请使用以下设置:

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

这篇关于设置管理端口时,Spring Boot的执行器不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 21:10