在 application.yml 中使用 servlet 参数测试 spring 启动应用程序
Test spring boot app with servlet parameters in application.yml
在application.yml中有如下参数:
server:
context-parameters:
appCode: MYAPPCODE
该参数由第三方库读取。当 运行 on embedded Tomcat 时,该参数在 ServletContext 中可用。但是运行在SpringRunner上测试时,ServletContext没有参数。
这里是测试的相关部分class。
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
@AutoConfigureMockMvc
public class RestControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
private void create() {
String content = createContent();
mockMvc.perform(post("/api/entity/create").content(content))
.andExpect(jsonPath("id").isNumber());
}
}
如何配置测试 class 以便使用来自 application.yml 的上下文参数设置模拟的 ServletContext?
目前,为了克服这个问题,我在测试中做了以下解决方法class。
@Autowired
private ServletContext servletContext;
@Autowired
private ServerProperties serverProperties;
@Before
public void setup() throws Exception {
Map<String, String> params = serverProperties.getContextParameters();
new InitParameterConfiguringServletContextInitializer(params)
.onStartup(servletContext);
}
How can I configure the test class so that the mocked ServletContext
is set with the context parameters from the application.yml
?
AFAIK,目前在使用 WebEnvironment.MOCK
(即 @SpringBootTest
的默认模式)时这是不可能的,因为 WebApplicationContext
使用的 MockServletContext
由 Spring Boot 是 plain vanilla(即,未填充外部值)。
因此,您的 "workaround" 是唯一的解决方案。
在application.yml中有如下参数:
server:
context-parameters:
appCode: MYAPPCODE
该参数由第三方库读取。当 运行 on embedded Tomcat 时,该参数在 ServletContext 中可用。但是运行在SpringRunner上测试时,ServletContext没有参数。
这里是测试的相关部分class。
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
@AutoConfigureMockMvc
public class RestControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
private void create() {
String content = createContent();
mockMvc.perform(post("/api/entity/create").content(content))
.andExpect(jsonPath("id").isNumber());
}
}
如何配置测试 class 以便使用来自 application.yml 的上下文参数设置模拟的 ServletContext?
目前,为了克服这个问题,我在测试中做了以下解决方法class。
@Autowired
private ServletContext servletContext;
@Autowired
private ServerProperties serverProperties;
@Before
public void setup() throws Exception {
Map<String, String> params = serverProperties.getContextParameters();
new InitParameterConfiguringServletContextInitializer(params)
.onStartup(servletContext);
}
How can I configure the test class so that the mocked
ServletContext
is set with the context parameters from theapplication.yml
?
AFAIK,目前在使用 WebEnvironment.MOCK
(即 @SpringBootTest
的默认模式)时这是不可能的,因为 WebApplicationContext
使用的 MockServletContext
由 Spring Boot 是 plain vanilla(即,未填充外部值)。
因此,您的 "workaround" 是唯一的解决方案。