title: Unit Test Spring Boot MessageSource
body: <p>I am using MessageSource in managing my error messages for my application.</p>
  
  <p>My error messages are inside the file <strong>error_messages.properties</strong> in <strong>src/main/resources/messages</strong>.</p>
  
  <p>Below is my configuration for my MessageSource</p>
  
  <pre><code>@Configuration
  @EntityScan("mypackage")
  @EnableJpaRepositories("mypackage")
  @ComponentScan(basePackages = {
          "mypackage"})
  public class DataConfig {
  
      @Bean
      public MessageSource messageSource() {
          ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
          messageSource.setBasenames("messages/error_messages");
          messageSource.setDefaultEncoding("UTF-8");
          return messageSource;
      }
  
  }
  </code></pre>
  
  <p>Below is my component in loading and using the MessageSource (based on <a href="https://gist.github.com/jonikarppinen/0d600b0c82edce890310" rel="nofollow noreferrer">this</a>)</p>
  
  <pre><code>@Component
  public class ErrorMessages {
  
      @Autowired
      private MessageSource messageSource;
  
      private MessageSourceAccessor accessor;
  
      @PostConstruct
      private void init() {
          accessor = new MessageSourceAccessor(messageSource);
      }
  
      public String get(String code) {
          return accessor.getMessage(code);
      }
  
  }
  </code></pre>
  
  <p>Now this is my Service layer.</p>
  
  <pre><code>@Service
  public class MyServiceImpl implements MyService{
  
      @Autowired
      private ErrorMessages errorMessages;
  
      @Override
      public String getExampleMessage(){
          return String.format(errorMessages.get("default.error"), "default");
      }
  
  }
  </code></pre>
  
  <p>my properties file</p>
  
  <pre><code>default.error=Default error with some default message %s.
  </code></pre>
  
  <p>This works fine when I run the application. Now my problem is when I run this in my unit test, I want it to actually fetch the error message from the property file. Since it's a MockBean I have to stub a return value for it and I don't want to do that.</p>
  
  <p>How do I do it?</p>
  
  <p>Below is my test.</p>
  
  <pre><code>@RunWith(SpringRunner.class)
  public class MyServiceImplTest {
  
      @TestConfiguration
      static class MyServiceImplTestContextConfiguration {
          @Bean
          public MyService myService() {
              return new MyServiceImpl();
          }
      }
  
      @Autowired
      private MyService myService;
  
      // I want to avoid mocking this.
      @MockBean
      private ErrorMessages errorMessages;
  
      @Test
      public void testGetExampleMessage() {
          String expected = "Default error with some default message default.";
          assertEquals(expected, myService.getExampleMessage());
      }
  
  }
  </code></pre>