简体   繁体   English

如何在Spring REST文档中切换语言环境?

[英]How to switch locale in Spring REST docs?

I have a @RestController where one of the arguments of a controller method is Locale 我有一个@RestController ,其中控制器方法的参数之一是Locale

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

I have a working integration test (using RestAssured) where I can switch locale by setting the Accept-Language header. 我有一个正在运行的集成测试(使用RestAssured),可以通过设置Accept-Language标头来切换语言环境。

I now want to document this using Spring REST docs as well. 我现在也想使用Spring REST文档对此进行记录。 Setting the header in this case (using MockMvc) does not work. 在这种情况下(使用MockMvc)设置标题无效。

My test something like this: 我的测试是这样的:

@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();
        }
    }
}

Is there some bean that I need to explicitly add to my test context that does the locale injection? 是否有一些我需要显式添加到进行语言环境注入的测试上下文中的bean?

I am using Spring Boot 1.3.3 (which has Spring 4.2.5) 我正在使用Spring Boot 1.3.3(具有Spring 4.2.5)

You can set the Locale using the locale(Locale) method on the request builder: 您可以设置Locale使用locale(Locale)的要求构建器方法:

mockMvc.perform(
    get("/")
        .accept(MediaType.APPLICATION_JSON)
        .locale(Locale.GERMAN))
    .andExpect(status().isOk())
    .andDo(document("example"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM