0

I have a @RestController where one of the arguments of a controller method is 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.

I now want to document this using Spring REST docs as well. Setting the header in this case (using MockMvc) does not work.

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?

I am using Spring Boot 1.3.3 (which has Spring 4.2.5)

Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211

1 Answers1

2

You can set the Locale using the locale(Locale) method on the request builder:

mockMvc.perform(
    get("/")
        .accept(MediaType.APPLICATION_JSON)
        .locale(Locale.GERMAN))
    .andExpect(status().isOk())
    .andDo(document("example"));
Andy Wilkinson
  • 108,729
  • 24
  • 257
  • 242
  • Thx. I ended up _also_ adding `.header("Accept-Language", "fr")` so that the `http-request.adoc` shows that header since users of my REST api need to do that to set the locale. – Wim Deblauwe Apr 06 '16 at 10:01