Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring messagesource while testing

i have message source defined in my java config as :

@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;
}

it works fine when using site and messages are displayed correctly, but when trying to write spring test with :

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

and a test class that simply extends it, i get error Can't find bundle for base name /i18n/ir/kia/industry/webapp/entity.

it works fine when starting tomcat and using message source in jsp files, but no luck when testing it. i have tried moving i18n folder under WEB-INF but it did not help it neither.

the target folder looks like this and please do not tell me add i18n folder to target resources ...

enter image description here

like image 753
alizelzele Avatar asked Oct 20 '22 17:10

alizelzele


1 Answers

i managed to solve the problem by removing the message source base names using spring profile feature. i changed the message source part to :

@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;
}

and add test profile to my test unit with

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

that when i was able to run my tests, but that is a way around for solving problem. i'm still confused for what was the reason of error in the first place. it that some sort of bug? or i'm doing something wrong?

like image 184
alizelzele Avatar answered Oct 22 '22 08:10

alizelzele