Spring Boot:如何将application.conperties中的server.contextPath注入MockServletContext

时间:2018-03-28 13:47:36

标签: spring-boot swagger springfox contextpath

在application.properties中,我配置了server.contextPath=/app-service

不幸的是,这个值在测试环境中不存在:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { Application.class, SwaggerConfig.class })
@WebAppConfiguration
public class Swagger2MarkupTest {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Before
    public void setUp() {
        this.context.getServletContext().getContextPath(); // null
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
    }
}

我需要使用默认情况下使用的Swagger Docket的contextPath  springfox.documentation.spring.web.paths.RelativePathProvider通过

确定contextPath
  @Override
  protected String applicationPath() {
    return isNullOrEmpty(servletContext.getContextPath()) ? ROOT : servletContext.getContextPath();
  }

所有关于RelativePathProvider的内容都比单元测试早得多。它不是将contextPath注入单元测试本身,因为它已经很晚,因为RelativePathProvider已经为SwaggerConfiguration调用了servletContext.getContextPath()

1 个答案:

答案 0 :(得分:0)

你可以通过多种方式实现这一目标,其中有两个:

  1. 注入弹簧Environment并获取属性值:

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = { Application.class, SwaggerConfig.class })
    @WebAppConfiguration
    public class Swagger2MarkupTest {
    
        @Autowired
        private WebApplicationContext context;
    
        @Autowired
        private Environment environment;
    
        private MockMvc mockMvc;
    
        @Before
        public void setUp() {
            environment.getProperty("server.contextPath"); // should return /app-service
            this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
        }
    }
    
  2. 使用@Value

    注入它
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = { Application.class, SwaggerConfig.class })
    @WebAppConfiguration
    public class Swagger2MarkupTest {
    
        @Autowired
        private WebApplicationContext context;
    
        @Value("server.contextPath")
        private String contextPath; // should populate with /app-service
    
        private MockMvc mockMvc;
    
        @Before
        public void setUp() {
            this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
        }
    }