0

我有@RestController一个控制器方法的参数之一是Locale

@RequestMapping("/{id}")
public Survey getSurvey( @PathVariable("id") SurveyId surveyId, 
                         Locale locale ) { ... }

我有一个有效的集成测试(使用 RestAssured),我可以通过设置Accept-Language标题来切换语言环境。

我现在也想使用 Spring REST 文档来记录这一点。在这种情况下设置标头(使用 MockMvc)不起作用。

我的测试是这样的:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration
@WebAppConfiguration
public void SurveyControllerDocumentation {

    // Test methods here
    ...

    // Application context for documentation test
    @Configuration
    @EnableAutoConfiguration
    public static class TestConfiguration {
        @Bean
        public SurveyController controller(MessageSource messageSource) {
            return new SurveyController(userService(), messageSource, surveyService());
        }

        @Bean
        public UserService userService() {
            return mock(UserService.class);
        }

        @Bean
        public SurveyService surveyService() {
            return mock(SurveyService.class);
        }

        @Bean
        public CustomEditorsControllerAdvice customEditorsControllerAdvice() {
            return new CustomEditorsControllerAdvice();
        }

        @Bean
        public RestResponseEntityExceptionHandler exceptionHandler() {
            return new RestResponseEntityExceptionHandler();
        }
    }
}

是否有一些 bean 需要显式添加到执行语言环境注入的测试上下文中?

我正在使用 Spring Boot 1.3.3(具有 Spring 4.2.5)

4

1 回答 1

2

您可以Locale使用locale(Locale)请求构建器上的方法设置:

mockMvc.perform(
    get("/")
        .accept(MediaType.APPLICATION_JSON)
        .locale(Locale.GERMAN))
    .andExpect(status().isOk())
    .andDo(document("example"));
于 2016-04-06T08:57:57.317 回答