【问题标题】:Testing Spring Actuator Info Values测试 Spring 执行器信息值
【发布时间】:2022-02-04 09:27:28
【问题描述】:

我正在为我的执行器编写一些 mockMvc 单元测试。我目前有一个用于健康的,效果很好

class HealthTest {
  @Autowired
  private Mockmvc mockMvc;

  private ResultActions resultActions;

  @BeforeEach() throws Exception {
    resultActions = mockMvc.perform(get("/actuator/health"));
  }

  @Test
  void shouldReturnOk() throws Exception {
    resultActions.andExpect(jsonPath("status", is("UP")));
  }
}

这很好用。但是,当将相同的逻辑应用于“/actuator/info”时(字面上与健康类完全相同,仅更改了该路径(在 application.yml 中定义了配置,并且我已经手动查看了它,当我运行应用程序)我得到一个 200 状态,但没有 JSON,即使网页本身显示一个 JSON 对象。就像当我通过它运行它时,它得到一个空白页面,或者页面,但不是在 json格式。

编辑:所以配置在 main/application.yml 中。当我将配置复制到 test/application.yml 时,它可以工作。有没有办法让 mvc 指向我的主 application.yml?因为所有这些真正的测试都是我重复的测试配置

编辑 2:更好的评论格式:

management:
   endpoints:
    web:
     exposure:
     include:
     - info 

info:
 application:
   name: My application name

【问题讨论】:

    标签: java spring spring-boot testing spring-boot-actuator


    【解决方案1】:

    /actuator/info 提供您的自定义信息。默认为空信息。因此,您必须创建一个 Spring bean 来提供此信息,例如:

    import java.util.HashMap;
    import java.util.Map;
    
    import org.springframework.boot.actuate.info.Info;
    import org.springframework.boot.actuate.info.InfoContributor;
    import org.springframework.stereotype.Component;
    
    @Component
    public class BuildInfoContributor implements InfoContributor {
    
        @Override
        public void contribute(Info.Builder builder) {
            Map<String, String> data = new HashMap<>();
            data.put("version", "2.0.0.M7");
            builder.withDetails(data);
        }
    }
    

    并测试:

    @SpringBootTest
    @AutoConfigureMockMvc
    class Test {
    
        @Autowired
        private MockMvc mockMvc;
    
        private ResultActions resultActions;
    
        @BeforeEach()
        void setUp() throws Exception {
            resultActions = mockMvc.perform(MockMvcRequestBuilders.get("/actuator/info"));
        }
    
        @Test
        void shouldReturnOk() throws Exception {
            resultActions.andExpect(jsonPath("version", is("2.0.0.M7")));
        }
    }
     
    

    【讨论】:

    • 我的执行器信息目前确实有效,只是主 application.yml 有 ``` management: endpoints: web: exposure: include: - info: application: name: My application name `` `
    • 是的,如果你的测试/资源中有application.yml,你应该覆盖所有你需要的属性,包括management.endpoints.web.exposure.include。否则使用配置文件 - application-test.yml 定义,然后将合并两个文件中的所有属性。
    【解决方案2】:

    问题解决了。所以事实证明测试资源文件不能被称为application.yml,它需要它自己的配置文件,或者它完全覆盖了主要的。

    【讨论】:

      猜你喜欢
      • 2016-09-05
      • 1970-01-01
      • 2021-10-30
      • 2021-05-20
      • 2010-10-02
      • 2020-08-27
      • 2019-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多