스프링 MVC 2편(백엔드 웹 개발 활용 기술)

Ch03. 메시지, 국제화 - 스프링 메시지 소스 사용

webmaster 2022. 3. 13. 13:36
728x90
@SpringBootTest
public class MessagesSourceTest {

    @Autowired
    MessageSource ms;

    @Test
    public void helloMessage() throws Exception{
        String result = ms.getMessage("hello", null, null);
        assertThat(result).isEqualTo("안녕");
    }

    @Test
    public void notFoundMessageCode() throws Exception{
        assertThatThrownBy(()->ms.getMessage("no_code", null, null))
                .isInstanceOf(NoSuchMessageException.class);
    }


    @Test
    public void notFoundMessageCodeDefaultMessage(){
        String message = ms.getMessage("no_code", null, "기본 메시지", null);
        assertThat(message).isEqualTo("기본 메시지");
    }

    @Test
    public void argumentMessage(){
        String message = ms.getMessage("hello.name", new Object[]{"Spring"}, null);
        assertThat(message).isEqualTo("안녕 Spring");
    }

    @Test
    public void defaultLang(){
        assertThat(ms.getMessage("hello", null, null)).isEqualTo("안녕");
        assertThat(ms.getMessage("hello", null, Locale.KOREA)).isEqualTo("안녕");
    }

    @Test
    public void enLang(){
        assertThat(ms.getMessage("hello", null, Locale.ENGLISH)).isEqualTo("hello");
    }
}
  • ms.getMessage("hello", null, null)
    • code: hello
    • args: null
    • locale: null
  • 가장 단순한 테스트는 메시지 코드로 hello를 입력하고 나머지 값은 null을 입력했다.
  • locale 정보가 없으면 basename 에서 설정한 기본 이름 메시지 파일을 조회한다.
  • basename으로 messages를 지정했으므로 messages.properties 파일에서 데이터 조회한다.
  • 메시지가 없는 경우에는 NoSuchMessageException 이 발생한다.
  • 메시지가 없어도 기본 메시지( defaultMessage )를 사용하면 기본 메시지가 반환된다.
  • 메시지의 {0} 부분은 매개변수를 전달해서 치환할 수 있다.
728x90