title: Spring MVC Test with Validation JSR-303/349: Locale or accept-language does not work in testing
body: <p>I am working with Spring Framework 4.3.3 </p>
  
  <p>I have the following situation for a <code>@Controller</code> either for <code>POST</code> or <code>PUT</code></p>
  
  <p>For example for <code>POST</code> I have the following:</p>
  
  <pre><code>@PostMapping(value="/save",
               consumes=MediaType.APPLICATION_FORM_URLENCODED_VALUE,
               produces=MediaType.TEXT_HTML_VALUE)
  public String saveOne(@Validated @ModelAttribute Persona persona,
          BindingResult result,
          RedirectAttributes redirectAttributes){
  
      logger.info("saveOne: {}", persona.toString());
  
      if(result.hasErrors()){
          logger.error("# Errors: {}", result.getErrorCount());
          logger.error("result: {}", result.toString());
          return "persona/saveOne";
      }
  
      personaRestController.saveOne(persona);
  
      redirectAttributes.addFlashAttribute("message", "process.successful");
      return "redirect:/message";
  }
  </code></pre>
  
  <p>The app works how is expected, through a <code>Web Form</code> this <code>@PostMapping</code> either saves/persists the data or validates the data <strong>and</strong> if it is invalid the same web form is shown with the error messages for each field and based about <code>i18n</code> such as <code>English</code>, <code>Spanish</code> and <code>Portuguese</code>. It related with <code>JSR-439</code> </p>
  
  <p>About Java config infrastructure configuration I have the following:</p>
  
  <pre><code>@Bean
  public LocaleChangeInterceptor localeChangeInterceptor(){
          LocaleChangeInterceptor localeChangeInterceptor=new LocaleChangeInterceptor();
          localeChangeInterceptor.setParamName("language");
          //localeChangeInterceptor.setHttpMethods("post", "put");
          return localeChangeInterceptor;
  }
  
  @Bean(name="localeResolver")
  public LocaleResolver cookieLocaleResolver(){
          CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
          cookieLocaleResolver.setCookieName("language");
          cookieLocaleResolver.setDefaultLocale(new Locale("en","US"));
          return cookieLocaleResolver;
  }
  </code></pre>
  
  <p>And</p>
  
  <pre><code>@EnableWebMvc
  @Configuration
  public class WebMvcConfig extends WebMvcConfigurerAdapter {
  
  ...
  
      @Override
      public void addInterceptors(InterceptorRegistry registry) {
          registry.addInterceptor(localeChangeInterceptorConfig.localeChangeInterceptor());
      }
  </code></pre>
  
  <p>The problem is about <code>Spring MVC Test</code>. I have the following:</p>
  
  <pre><code>@Before
  public void setUp(){
      mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
  }
  
  ...
  
  @Test
  public void saveOneHtmlPostInvalidMaxTest() throws Exception {
  
      logger.info("saveOneHtmlPostInvalidMaxTest");
  
      resultActions = mockMvc.perform(post(url)
                  .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                  .locale(locale)
                  .header("accept-language", locale.toString())
                  .header("language", locale.toString())
                  .param("id", personaInvalidMax.getId())
                  .param("nombre", personaInvalidMax.getNombre())
                  .param("apellido", personaInvalidMax.getApellido())
                  ....
                  .andDo(print());
  </code></pre>
  
  <p><strong>Note</strong> observe:</p>
  
  <pre><code>                .locale(locale)
                  .header("accept-language", locale.toString())
                  .header("language", locale.toString())
  </code></pre>
  
  <p>Even when some of them have no sense, they are there because I am trying to resolve the following situation:</p>
  
  <p>The validation control from the server side works how is expected <em>until</em> some point. </p>
  
  <p><strong>First</strong></p>
  
  <p>I can confirm through <code>.andDo(print())</code> method that <code>MockHttpServletRequest</code> prints </p>
  
  <blockquote>
    <p>Headers = {Content-Type=[application/x-www-form-urlencoded],
    accept-language=[pt_BR], language=[pt_BR]}</p>
  </blockquote>
  
  <p>Observe <code>pt_BR</code></p>
  
  <p><strong>Second</strong></p>
  
  <p>The <code>@PostMapping</code> that contains:</p>
  
  <pre><code>if(result.hasErrors()){
      logger.error("# Errors: {}", result.getErrorCount());
      logger.error("result: {}", result.toString());
      return "persona/saveOne";
  }
  </code></pre>
  
  <p>Prints...</p>
  
  <blockquote>
    <p>7370 [Test worker] ERROR PersonaSaveOneController - result:
    org.springframework.validation.BeanPropertyBindingResult: 4 errors
    Field error in object 'persona' on field 'id': rejected value [0];
    codes [Size.persona.id,Size.id,Size.java.lang.String,Size]; arguments
    [org.springframework.context.support.DefaultMessageSourceResolvable:
    codes [persona.id,id]; arguments []; default message [id],3,3];
    default message [The size for the field must be between 3 and 3]</p>
  </blockquote>
  
  <p>Observe the <code>default message [id],3,3];
  default message [The size for the field must be between 3 and 3]</code></p>
  
  <p>Here two problems:</p>
  
  <ul>
  <li>The <code>locale</code> or <code>accept-language</code> are ignored</li>
  <li>The error messages prints always in English </li>
  </ul>
  
  <p>What I need is that the error data prints for example in <code>Portuguese</code> and <code>Spanish</code> according the <code>Locale</code> sent. It should returns the error messages for each field in an expected language, in this case <code>Portuguese</code></p>
  
  <p>Again, it works when I use directly the <code>Web Form</code>, but not through the Test. I am assuming that exists an internal Spring component that works through <code>production</code> and has not been defined for <code>Testing</code></p>
  
  <p>Therefore, what is need it to accomplish this approach?</p>
  
  <p>BTW: With the following (see I use <code>classpath:</code>), furthermore my <code>.properties</code> file are located in <code>src/main/resources</code></p>
  
  <pre><code>@Bean(name="messageSource")
  public ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource() {
          ReloadableResourceBundleMessageSource resource = new ReloadableResourceBundleMessageSource();
          resource.setBasenames(...
  "classpath:/com/manuel/jordan/validation/validation");
          resource.setDefaultEncoding("UTF-8");
          return resource;
  }
  </code></pre>
  
  <p>My <code>@Test</code> methods working around with <code>Rest</code> works fine about show and returning the error message according the <code>Locale</code> or <code>accept-language</code> defined (Access to <code>MessageSource</code> happens in the server side and works fine with the previous configuration). It just fails for <code>non-Rest</code> controllers </p>