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?
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)));
精彩评论