1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.codec;
19
20 import static org.junit.jupiter.api.Assertions.assertEquals;
21 import static org.junit.jupiter.api.Assertions.assertThrows;
22 import static org.junit.jupiter.api.Assertions.fail;
23
24 import java.util.Locale;
25
26 import org.junit.jupiter.api.Test;
27
28
29
30 public abstract class AbstractStringEncoderTest<T extends StringEncoder> {
31
32 protected T stringEncoder = createStringEncoder();
33
34 public void checkEncoding(final String expected, final String source) throws EncoderException {
35 assertEquals(expected, getStringEncoder().encode(source), "Source: " + source);
36 }
37
38 protected void checkEncodings(final String[][] data) throws EncoderException {
39 for (final String[] element : data) {
40 checkEncoding(element[1], element[0]);
41 }
42 }
43
44 protected void checkEncodingVariations(final String expected, final String... data) throws EncoderException {
45 for (final String element : data) {
46 checkEncoding(expected, element);
47 }
48 }
49
50 protected abstract T createStringEncoder();
51
52 public T getStringEncoder() {
53 return stringEncoder;
54 }
55
56 @Test
57 void testEncodeEmpty() throws Exception {
58 final Encoder encoder = getStringEncoder();
59 encoder.encode("");
60 encoder.encode(" ");
61 encoder.encode("\t");
62 }
63
64 @Test
65 void testEncodeNull() throws EncoderException {
66 final StringEncoder encoder = getStringEncoder();
67 encoder.encode(null);
68 }
69
70 @Test
71 void testEncodeWithInvalidObject() throws Exception {
72 final StringEncoder encoder = getStringEncoder();
73 assertThrows(EncoderException.class, () -> encoder.encode(Float.valueOf(3.4f)), "An exception was not thrown when we tried to encode a Float object");
74 }
75
76 @Test
77 void testLocaleIndependence() throws Exception {
78 final StringEncoder encoder = getStringEncoder();
79 final String[] data = { "I", "i" };
80 final Locale orig = Locale.getDefault();
81 final Locale[] locales = { Locale.ENGLISH, new Locale("tr"), Locale.getDefault() };
82 try {
83 for (final String element : data) {
84 String ref = null;
85 for (int j = 0; j < locales.length; j++) {
86 Locale.setDefault(locales[j]);
87 if (j <= 0) {
88 ref = encoder.encode(element);
89 } else {
90 String cur = null;
91 try {
92 cur = encoder.encode(element);
93 } catch (final Exception e) {
94 fail(Locale.getDefault().toString() + ": " + e.getMessage());
95 }
96 assertEquals(ref, cur, Locale.getDefault().toString() + ": ");
97 }
98 }
99 }
100 } finally {
101 Locale.setDefault(orig);
102 }
103 }
104 }