【发布时间】:2016-10-27 16:15:16
【问题描述】:
我有一个简单的 Spring MVC 控制器,它的 RequestMapping 是一个属性。这是一个包含控制器的罐子。下游应用会使用这个 jar 并使用公共端点,只有精确的 URL 可能因应用而异)
当我将我的 jar 包含到另一个应用程序中时,一切正常。该应用程序有一个属性或 yaml 文件,并且该属性已设置。我已验证端点工作正常。
但是,作为一名优秀的开发人员,我想做一个集成测试来验证由属性确定的 URL 是否正确公开。我可以在控制器中正确注入@Value,但@RequestMapping 中的${} 表达式不会被属性文件替换。我找到了几个线程(Spring Boot REST Controller Test with RequestMapping of Properties Value 和 @RequestMapping with placeholder not working)但要么他们不适用,要么我尝试了他们所说的但我无法让它工作。
命中静态 (iWork) 端点的测试有效,但从属性中提取的测试 (iDontWork) 无效。
(这是 Spring 4.2.6)
控制器
@RestController
@RequestMapping(value = {"/${appName}", "/iWork"})
public class Controller {
@Value("${appName}")
private String appName;
@RequestMapping(method= RequestMethod.GET)
public String handlerMethod (HttpServletRequest request) throws Exception {
// Proves the placeholder is injected in the class, but
// Not in the RequestMapping
assert appName != null;
assert !appName.equals("${appName}");
return "";
}
}
控制器测试
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class,
classes = { ControllerTest.Config.class })
public class ControllerTest {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.build();
}
@Configuration
@ComponentScan(basePackages = {"test"})
static class Config {
// because @PropertySource doesnt work in annotation only land
@Bean
PropertyPlaceholderConfigurer propConfig() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setLocation(new ClassPathResource("test.properties"));
return ppc;
}
}
@Test
public void testStaticEndpoint() throws Exception {
mvc.perform(get("/iWork")).andExpect(status().isOk());
}
@Test
public void testDynamicEndpoint() throws Exception {
mvc.perform(get("/iDontWork")).andExpect(status().isOk());
}
}
test.properties
appName = iDontWork
【问题讨论】:
标签: java spring spring-mvc junit