1

Trying to get Unit Tests to work when using Spring RestTemplate and I18N. Everything in the setup works fine for all the other test cases.

Based upon what I read, this is what I put into the Java Config:

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    return new LocaleChangeInterceptor();
}

@Bean
public DefaultAnnotationHandlerMapping handlerMapping() {
    DefaultAnnotationHandlerMapping mapping = new DefaultAnnotationHandlerMapping();
    Object[] interceptors = new Object[1];
    interceptors[0] = new LocaleChangeInterceptor();
    mapping.setInterceptors(interceptors);
    return mapping;
}

@Bean
public AnnotationMethodHandlerAdapter handlerAdapter() {
    return new AnnotationMethodHandlerAdapter();
}

Then in my usage with RestTemplate I have:

    public MyEntity createMyEntity(MyEntity bean) {
    Locale locale = LocaleContextHolder.getLocale();
    String localeString = "";
    if (locale != Locale.getDefault()) {
        localeString = "?locale=" + locale.getLanguage();
    }
    HttpEntity<MyEntity> req = new HttpEntity<MyEntity>(bean);
    ResponseEntity<MyEntity> response = restTemplate.exchange(restEndpoint + "/url_path" + localeString, HttpMethod.POST, req, MyEntity.class);
    return response.getBody();
}

While this could be cleaned up a bit, it should work - but the LocalChangeInterceptor never gets invoked. I am debugging this now and will post again as soon as I figure it out - but in the hope this is a race condition that I lose - does anyone know why?

JoeG
  • 7,191
  • 10
  • 60
  • 105

1 Answers1

1

Was lucky and stumbled upon this thread. One of the notes clued me into the right direction. You don't need all those beans in the Java Config. But if you are using @EnableWebMvc as I am, but I didn't know it was important enough to even mention, all you need to do in your Java Config is:

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    return new LocaleChangeInterceptor();
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LocaleChangeInterceptor());
    super.addInterceptors(registry);
}

Add the one bean for the Interceptor and then override the method to add the interceptor. Here my configuration class (annotated with @Configuration and @EnableWebMvc) also extends WebMvcConfigurerAdapter, which should be common usage.

This, at least, worked for me. Hope it may help someone else.

Community
  • 1
  • 1
JoeG
  • 7,191
  • 10
  • 60
  • 105