|
| 1 | +package com.baeldung.namedformatting; |
| 2 | + |
| 3 | +import org.apache.commons.text.StrSubstitutor; |
| 4 | +import org.junit.jupiter.api.Test; |
| 5 | + |
| 6 | +import java.util.HashMap; |
| 7 | +import java.util.Map; |
| 8 | + |
| 9 | +import static org.assertj.core.api.Assertions.assertThat; |
| 10 | + |
| 11 | +class NamedFormatterUnitTest { |
| 12 | + private static final String TEMPLATE = "Text: [${text}] Number: [${number}] Text again: [${text}]"; |
| 13 | + |
| 14 | + @Test |
| 15 | + void givenTemplateWithNamedParam_whenCallingCommonsTextStrSubstitutor_shouldGetExpectedResult() { |
| 16 | + Map<String, Object> params = new HashMap<>(); |
| 17 | + params.put("text", "It's awesome!"); |
| 18 | + params.put("number", 42); |
| 19 | + String result = StrSubstitutor.replace(TEMPLATE, params, "${", "}"); |
| 20 | + assertThat(result).isEqualTo("Text: [It's awesome!] Number: [42] Text again: [It's awesome!]"); |
| 21 | + } |
| 22 | + |
| 23 | + @Test |
| 24 | + void givenTemplateWithNamedParam_whenCallingCommonsTextStrSubstitutorWithParameterNames_shouldNotWorkAsExpected() { |
| 25 | + Map<String, Object> params = new HashMap<>(); |
| 26 | + params.put("text", "'${number}' is a placeholder."); |
| 27 | + params.put("number", 42); |
| 28 | + String result = StrSubstitutor.replace(TEMPLATE, params, "${", "}"); |
| 29 | + |
| 30 | + assertThat(result).isNotEqualTo("Text: ['${number}' is a placeholder.] Number: [42] Text again: ['${number}' is a placeholder.]"); |
| 31 | + |
| 32 | + assertThat(result).isEqualTo("Text: ['42' is a placeholder.] Number: [42] Text again: ['42' is a placeholder.]"); |
| 33 | + } |
| 34 | + |
| 35 | + @Test |
| 36 | + void givenTemplateWithNamedParam_whenCallingNamedFormatter_shouldGetExpectedResult() { |
| 37 | + Map<String, Object> params = new HashMap<>(); |
| 38 | + params.put("text", "It's awesome!"); |
| 39 | + params.put("number", 42); |
| 40 | + String result = NamedFormatter.format(TEMPLATE, params); |
| 41 | + assertThat(result).isEqualTo("Text: [It's awesome!] Number: [42] Text again: [It's awesome!]"); |
| 42 | + |
| 43 | + params.put("text", "'${number}' is a placeholder."); |
| 44 | + result = NamedFormatter.format(TEMPLATE, params); |
| 45 | + assertThat(result).isEqualTo("Text: ['${number}' is a placeholder.] Number: [42] Text again: ['${number}' is a placeholder.]"); |
| 46 | + } |
| 47 | +} |
0 commit comments