@@ -195,6 +195,7 @@ public void enumToString() {
195195 Util .compareActualVsExpectedJsonArrays (actualJsonArray , expectedJsonArray );
196196 }
197197
198+ @ Test
198199 public void wrap () {
199200 /**
200201 * Wrap should handle enums exactly the same way as the JSONObject(Object)
@@ -218,4 +219,54 @@ public void wrap() {
218219 expectedJsonObject = new JSONObject (expectedStr );
219220 Util .compareActualVsExpectedJsonObjects (jsonObject , expectedJsonObject );
220221 }
222+
223+ @ Test
224+ public void enumAPI () {
225+ /**
226+ * Exercise the proposed enum API methods
227+ */
228+ MyEnumClass myEnumClass = new MyEnumClass ();
229+ myEnumClass .setMyEnum (MyEnum .VAL1 );
230+ MyEnumField myEnumField = MyEnumField .VAL2 ;
231+
232+ JSONObject jsonObject = new JSONObject ();
233+ jsonObject .put ("strKey" , "value" );
234+ jsonObject .put ("enumKey" , myEnumField );
235+ jsonObject .put ("enumClassKey" , myEnumClass );
236+
237+ // get a plain old enum
238+ MyEnumField actualEnum = jsonObject .getEnum (MyEnumField .class , "enumKey" );
239+ assertTrue ("get myEnumField" , actualEnum == MyEnumField .VAL2 );
240+
241+ // try to get the wrong value
242+ try {
243+ actualEnum = jsonObject .getEnum (MyEnumField .class , "strKey" );
244+ assertTrue ("should throw an exception for wrong key" , false );
245+ } catch (Exception ignored ) {}
246+
247+ // get a class that contains an enum
248+ MyEnumClass actualEnumClass = (MyEnumClass )jsonObject .get ("enumClassKey" );
249+ assertTrue ("get enum" , actualEnumClass .getMyEnum () == MyEnum .VAL1 );
250+
251+ // opt a plain old enum
252+ actualEnum = jsonObject .optEnum (MyEnumField .class , "enumKey" );
253+ assertTrue ("opt myEnumField" , actualEnum == MyEnumField .VAL2 );
254+
255+ // opt the wrong value
256+ actualEnum = jsonObject .optEnum (MyEnumField .class , "strKey" );
257+ assertTrue ("opt null" , actualEnum == null );
258+
259+ // opt a class that contains an enum
260+ actualEnumClass = (MyEnumClass )jsonObject .opt ("enumClassKey" );
261+ assertTrue ("get enum" , actualEnumClass .getMyEnum () == MyEnum .VAL1 );
262+
263+ // opt with default a plain old enum
264+ actualEnum = jsonObject .optEnum (MyEnumField .class , "enumKey" , null );
265+ assertTrue ("opt myEnumField" , actualEnum == MyEnumField .VAL2 );
266+
267+ // opt with default the wrong value
268+ actualEnum = jsonObject .optEnum (MyEnumField .class , "strKey" , null );
269+ assertTrue ("opt null" , actualEnum == null );
270+
271+ }
221272}
0 commit comments