gpt4 book ai didi

spring-mvc - Spring SimpleFormController 中的 Java junit 测试更改区域设置

转载 作者:行者123 更新时间:2023-12-04 21:24:12 26 4
gpt4 key购买 nike

对于 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 测试策略吗?

最佳答案

您需要在测试中再次获取 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)));

关于spring-mvc - Spring SimpleFormController 中的 Java junit 测试更改区域设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6527377/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com