RequestMapping占位符在JUnit测试中不起作用

时间:2016-06-24 23:55:04

标签: java spring spring-mvc junit

我有一个简单的Spring MVC控制器,其RequestMapping是一个属性。这是一个包含控制器的jar。下游应用程序将使用此jar并使用公共端点,只有精确的URL可能因app而异

当我将jar包含到另一个应用程序中时,一切正常。该应用程序有一个属性或yaml文件,并设置属性。我已经验证端点工作正常。

但是,作为一名优秀的开发人员,我想进行集成测试,以验证属性确定的URL是否正确公开。我可以正确地注入控制器中的@Value,但@RequestMapping中的$ {}表达式不会从属性文件中替换。我找到了几个帖子(Spring Boot REST Controller Test with RequestMapping of Properties Value@RequestMapping with placeholder not working)但要么他们不申请,要么我尝试了他们说的话,我无法让它发挥作用。

命中静态(iWork)端点的测试有效,但从属性(iDontWork)中提取的测试不起作用。

(这是春季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 "";
    }
}

ControllerTest

@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

2 个答案:

答案 0 :(得分:2)

你“只是”缺少

@EnableWebMvc

@Configuration课程上。没有它,Spring的Mock MVC堆栈将使用DefaultAnnotationHandlerMapping注册您的控制器处理程序方法,这不足以解析@RequestMapping中的占位符。

如果你提供它,Mock MVC将使用RequestMappingHandlerMapping,这是。

答案 1 :(得分:0)

  

您需要在创建mockMvc时添加占位符值,如下所示。

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders.standaloneSetup(accountController)
                .addPlaceholderValue("propertyName", "propertyValue")
                .build();
}
相关问题