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 java.util.Locale;
21
22 import org.junit.Assert;
23 import org.junit.Test;
24
25
26
27
28 public abstract class StringEncoderAbstractTest<T extends StringEncoder> {
29
30 protected T stringEncoder = this.createStringEncoder();
31
32 public void checkEncoding(final String expected, final String source) throws EncoderException {
33 Assert.assertEquals("Source: " + source, expected, this.getStringEncoder().encode(source));
34 }
35
36 protected void checkEncodings(final String[][] data) throws EncoderException {
37 for (final String[] element : data) {
38 this.checkEncoding(element[1], element[0]);
39 }
40 }
41
42 protected void checkEncodingVariations(final String expected, final String data[]) throws EncoderException {
43 for (final String element : data) {
44 this.checkEncoding(expected, element);
45 }
46 }
47
48 protected abstract T createStringEncoder();
49
50 public T getStringEncoder() {
51 return this.stringEncoder;
52 }
53
54 @Test
55 public void testEncodeEmpty() throws Exception {
56 final Encoder encoder = this.getStringEncoder();
57 encoder.encode("");
58 encoder.encode(" ");
59 encoder.encode("\t");
60 }
61
62 @Test
63 public void testEncodeNull() throws Exception {
64 final StringEncoder encoder = this.getStringEncoder();
65 try {
66 encoder.encode(null);
67 } catch (final EncoderException ee) {
68
69 }
70 }
71
72 @Test
73 public void testEncodeWithInvalidObject() throws Exception {
74 boolean exceptionThrown = false;
75 try {
76 final StringEncoder encoder = this.getStringEncoder();
77 encoder.encode(new Float(3.4));
78 } catch (final Exception e) {
79 exceptionThrown = true;
80 }
81 Assert.assertTrue("An exception was not thrown when we tried to encode " + "a Float object", exceptionThrown);
82 }
83
84 @Test
85 public void testLocaleIndependence() throws Exception {
86 final StringEncoder encoder = this.getStringEncoder();
87
88 final String[] data = {"I", "i",};
89
90 final Locale orig = Locale.getDefault();
91 final Locale[] locales = {Locale.ENGLISH, new Locale("tr"), Locale.getDefault()};
92
93 try {
94 for (final String element : data) {
95 String ref = null;
96 for (int j = 0; j < locales.length; j++) {
97 Locale.setDefault(locales[j]);
98 if (j <= 0) {
99 ref = encoder.encode(element);
100 } else {
101 String cur = null;
102 try {
103 cur = encoder.encode(element);
104 } catch (final Exception e) {
105 Assert.fail(Locale.getDefault().toString() + ": " + e.getMessage());
106 }
107 Assert.assertEquals(Locale.getDefault().toString() + ": ", ref, cur);
108 }
109 }
110 }
111 } finally {
112 Locale.setDefault(orig);
113 }
114 }
115
116 }