01: /*
02: * Copyright (C) 2004 Joe Walnes.
03: * Copyright (C) 2006, 2007 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 14. July 2004 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.converters.reflection;
13:
14: import junit.framework.TestCase;
15:
16: import java.lang.reflect.Field;
17: import java.lang.reflect.Modifier;
18: import java.util.Iterator;
19:
20: public class FieldDictionaryTest extends TestCase {
21:
22: private FieldDictionary fieldDictionary;
23:
24: protected void setUp() throws Exception {
25: super .setUp();
26: fieldDictionary = new FieldDictionary();
27: }
28:
29: static class SomeClass {
30: private String a;
31: private String c;
32: private transient String b;
33: private static String d;
34: private String e;
35: }
36:
37: public void testListsFieldsInClassInDefinitionOrder() {
38: Iterator fields = fieldDictionary.fieldsFor(SomeClass.class);
39: assertEquals("a", getNonStaticFieldName(fields));
40: assertEquals("c", getNonStaticFieldName(fields));
41: assertEquals("b", getNonStaticFieldName(fields));
42: assertEquals("e", getNonStaticFieldName(fields));
43: assertFalse("No more fields should be present", fields
44: .hasNext());
45: }
46:
47: static class SpecialClass extends SomeClass {
48: private String brilliant;
49: }
50:
51: public void testIncludesFieldsInSuperClasses() {
52: Iterator fields = fieldDictionary.fieldsFor(SpecialClass.class);
53: assertEquals("a", getNonStaticFieldName(fields));
54: assertEquals("c", getNonStaticFieldName(fields));
55: assertEquals("b", getNonStaticFieldName(fields));
56: assertEquals("e", getNonStaticFieldName(fields));
57: assertEquals("brilliant", getNonStaticFieldName(fields));
58: assertFalse("No more fields should be present", fields
59: .hasNext());
60: }
61:
62: class InnerClass { // note: no static makes this an inner class, not nested class.
63: private String someThing;
64: }
65:
66: public void testIncludesOuterClassReferenceForInnerClass() {
67: Iterator fields = fieldDictionary.fieldsFor(InnerClass.class);
68: assertEquals("someThing", getNonStaticFieldName(fields));
69: Field innerField = ((Field) fields.next());
70: assertEquals("this$0", innerField.getName());
71: assertEquals(FieldDictionaryTest.class, innerField.getType());
72: assertFalse("No more fields should be present", fields
73: .hasNext());
74: }
75:
76: private static String getNonStaticFieldName(Iterator fields) {
77: final Field field = (Field) fields.next();
78: // JRockit declares static fields first, XStream will ignore them anyway
79: if ((field.getModifiers() & Modifier.STATIC) > 0) {
80: return getNonStaticFieldName(fields);
81: }
82: return field.getName();
83: }
84: }
|