For SpringMVC, I have a SimpleFormController with a simple method that changes the language for the user by changing locale (i18n).
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);
localeResolver.setLocale(request, response,
(Locale) localeEditor.getValue());
}
}
And the code works great when using the application . However, I want to run a Junit test for this method, and here is what I have so far found:
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 "fr_CA" not "zh_CN". Can anyone provide a better Junit testing strategy for this?
source
share