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 = this.createStringEncoder();
33
34 public void checkEncoding(final String expected, final String source) throws EncoderException {
35 assertEquals(expected, this.getStringEncoder().encode(source), "Source: " + source);
36 }
37
38 protected void checkEncodings(final String[][] data) throws EncoderException {
39 for (final String[] element : data) {
40 this.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 this.checkEncoding(expected, element);
47 }
48 }
49
50 protected abstract T createStringEncoder();
51
52 public T getStringEncoder() {
53 return this.stringEncoder;
54 }
55
56 @Test
57 public void testEncodeEmpty() throws Exception {
58 final Encoder encoder = this.getStringEncoder();
59 encoder.encode("");
60 encoder.encode(" ");
61 encoder.encode("\t");
62 }
63
64 @Test
65 public void testEncodeNull() throws EncoderException {
66 final StringEncoder encoder = this.getStringEncoder();
67 encoder.encode(null);
68 }
69
70 @Test
71 public void testEncodeWithInvalidObject() throws Exception {
72 final StringEncoder encoder = this.getStringEncoder();
73 assertThrows(EncoderException.class, () -> encoder.encode(Float.valueOf(3.4f)),
74 "An exception was not thrown when we tried to encode a Float object");
75 }
76 @Test
77 public void testLocaleIndependence() throws Exception {
78 final StringEncoder encoder = this.getStringEncoder();
79
80 final String[] data = { "I", "i" };
81
82 final Locale orig = Locale.getDefault();
83 final Locale[] locales = { Locale.ENGLISH, new Locale("tr"), Locale.getDefault() };
84
85 try {
86 for (final String element : data) {
87 String ref = null;
88 for (int j = 0; j < locales.length; j++) {
89 Locale.setDefault(locales[j]);
90 if (j <= 0) {
91 ref = encoder.encode(element);
92 } else {
93 String cur = null;
94 try {
95 cur = encoder.encode(element);
96 } catch (final Exception e) {
97 fail(Locale.getDefault().toString() + ": " + e.getMessage());
98 }
99 assertEquals(ref, cur, Locale.getDefault().toString() + ": ");
100 }
101 }
102 }
103 } finally {
104 Locale.setDefault(orig);
105 }
106 }
107
108 }