【问题标题】:spring messagesource while testing测试时弹出消息源
【发布时间】:2015-04-17 23:32:44
【问题描述】:

我在我的 java 配置中定义了消息源:

@Bean(name = "messageSource")
public MessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasenames(
            "/i18n/ir/kia/industry/webapp/entity",
            "/i18n/ir/kia/industry/webapp/formErrors",
            "/i18n/ir/kia/industry/webapp/frontend",
            "/i18n/ir/kia/industry/webapp/frontendPages");
    return messageSource;
}

在使用站点时可以正常工作,并且消息显示正确,但是在尝试使用以下方式编写弹簧测试时:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestContext.class, SpringMVC.class})
@WebAppConfiguration
public abstract class AbstractTestClass {
  protected MockMvc mockMvc;
  @Autowired
  private WebApplicationContext webApplicationContext;

  @Before
  public void setUp() throws Exception {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
  }
}

和一个简单扩展它的测试类,我得到错误Can't find bundle for base name /i18n/ir/kia/industry/webapp/entity

在启动tomcat并在jsp文件中使用消息源时它工作正常,但在测试时没有运气。我曾尝试在 WEB-INF 下移动 i18n 文件夹,但也无济于事。

目标文件夹是这样的,请不要告诉我添加 i18n 文件夹到目标资源...

【问题讨论】:

  • SpringMVC.class中有messageSource吗?
  • 它在SpringLocalization.class 中,在SpringMVC.class 中导入。 messagesource bean 显然已被读取,因为它可以看到其中定义的基本名称。我从中删除了基本名称并且代码可以正常工作,但是测试时有什么问题??!
  • 好的 - 将资源添加到您的类路径中,测试应该能够找到它们
  • @farrellmr 问题是资源到位。该网站正常运行并查看所有资源。我将添加目标文件夹的图片

标签: java spring unit-testing spring-mvc spring-test-mvc


【解决方案1】:

我设法通过使用弹簧配置文件功能删除消息源基本名称来解决问题。我将消息源部分更改为:

@Bean(name = "messageSource")
@Profile(value = {"dev","prod"})
public MessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasenames(
            "/i18n/ir/kia/industry/webapp/entity",
            "/i18n/ir/kia/industry/webapp/formErrors",
            "/i18n/ir/kia/industry/webapp/frontend",
            "/i18n/ir/kia/industry/webapp/frontendPages");
    messageSource.setCacheSeconds(5);
    return messageSource;
}

@Bean(name = "messageSource")
@Profile("test")
public MessageSource testMessageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    return messageSource;
}

并将测试配置文件添加到我的测试单元

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestContext.class, SpringMVC.class})
@WebAppConfiguration
@ActiveProfiles("test")
public abstract class AbstractTestClass {

当我能够运行我的测试时,但这是解决问题的一种方法。我仍然对首先出错的原因感到困惑。 它是某种错误?还是我做错了什么?

【讨论】:

  • 只是我必须做的一个注释:messageSource.setBasename("messages") 其中messages是具有转换属性以使其工作的文件。
猜你喜欢
  • 2019-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-28
  • 2013-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多