Java junit测试更改Spring SimpleFormController中的Locale

时间:2011-06-29 21:17:52

标签: spring-mvc java-ee

对于SpringMVC,我有一个SimpleFormController,它有一个简单的方法,通过改变语言环境(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());
    }
}

代码在使用应用时效果很好。但是我想对这个方法进行Junit测试,以下是我到目前为止所提出的:

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());
}

}

但它打印出“fr_CA”而不是“zh_CN”。有人可以为此提供更好的Junit测试策略吗?

1 个答案:

答案 0 :(得分:2)

您需要再次获取测试中的localeResolver

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)));