Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java junit test change Locale in Spring SimpleFormController

For a SpringMVC, I have a SimpleFormController with a simple method which changes language for user by changing locale (i18n).

    //localization
public void localize(HttpServletRequest request, HttpServletResponse response, String language) throws Exception {
    LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);                

    if (localeResolver != null) {
        LocaleEditor localeEditor = new LocaleEditor();
        localeEditor.setAsText(language);

        // set the new locale
        localeResolver.setLocale(request, response,
                (Locale) localeEditor.getValue());
    }
}

And the code works fine while using the app. However I want to do the Junit test for this method and the following is what I have come up with so far:

public class LoginPostControllerTest extends TestCase {
public void testLocalize() throws Exception {

    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    Locale frenchLocale = Locale.CANADA_FRENCH;

    mockRequest.addPreferredLocale(frenchLocale);

    SessionLocaleResolver localeResolver = new SessionLocaleResolver();

    mockRequest.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, localeResolver);

    String language = "zh_CN";

    LoginPostController loginPostControllerTest = new LoginPostController();

    loginPostControllerTest.localize(mockRequest, mockResponse, language);
    System.out.println(mockRequest.getLocale().toString());
}

}

but it prints out "fr_CA" not "zh_CN". Can somebody provide a better Junit test strategy for this?

like image 690
Gurkhali Avatar asked Nov 05 '22 19:11

Gurkhali


1 Answers

you need obtain again the localeResolver on your test

LocaleResolver resolver = RequestContextUtils.getLocaleResolver(mockRequest);
System.out.println(mockRequest.getLocale().toString());
System.out.println(resolver.resolveLocale(mockRequest).toString());
assertTrue(!mockRequest.getLocale().equals(resolver.resolveLocale(mockRequest)));
like image 189
sergio Avatar answered Nov 09 '22 12:11

sergio