01: /*
02: * Copyright (C) 2008 XStream Committers.
03: * All rights reserved.
04: *
05: * The software in this package is published under the terms of the BSD
06: * style license a copy of which has been included with this distribution in
07: * the LICENSE.txt file.
08: *
09: * Created on 12. February 2008 by Joerg Schaible
10: */
11: package com.thoughtworks.xstream.converters.enums;
12:
13: import com.thoughtworks.xstream.XStream;
14: import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
15:
16: import junit.framework.TestCase;
17:
18: import java.util.ArrayList;
19: import java.util.List;
20:
21: // ***** READ THIS *****
22: // This class will only compile with JDK 1.5.0 or above as it test Java enums.
23: // If you are using an earlier version of Java, just don't try to build this class. XStream
24: // should work fine without it.
25:
26: /**
27: * @author Jörg Schaible
28: */
29: public class EnumMapperTest extends TestCase {
30:
31: private XStream xstream;
32:
33: protected void setUp() throws Exception {
34: super .setUp();
35: xstream = new XStream();
36: xstream.alias("simple", SimpleEnum.class);
37: xstream.alias("polymorphic", PolymorphicEnum.class);
38: }
39:
40: static class Bowl {
41: Fruit fruit;
42: }
43:
44: public void testSupportsDefaultImplementationToBeAnEnum() {
45: xstream.alias("bowl", Bowl.class);
46: xstream.addDefaultImplementation(PolymorphicEnum.class,
47: Fruit.class);
48: String expectedXml = "" // force format
49: + "<bowl>\n" + " <fruit>B</fruit>\n" + "</bowl>";
50: Bowl in = new Bowl();
51: in.fruit = PolymorphicEnum.B;
52: assertEquals(expectedXml, xstream.toXML(in));
53: Bowl out = (Bowl) xstream.fromXML(expectedXml);
54: assertSame(out.fruit, PolymorphicEnum.B);
55: }
56:
57: static class TypeWithEnums {
58: PolymorphicEnum poly;
59: @XStreamAsAttribute
60: SimpleEnum simple;
61: }
62:
63: public void testSupportsEnumAsAttribute() {
64: xstream.alias("type", TypeWithEnums.class);
65: xstream.useAttributeFor(PolymorphicEnum.class);
66: xstream.autodetectAnnotations(true);
67: String expectedXml = "<type poly=\"B\" simple=\"GREEN\"/>";
68: TypeWithEnums in = new TypeWithEnums();
69: in.poly = PolymorphicEnum.B;
70: in.simple = SimpleEnum.GREEN;
71: assertEquals(expectedXml, xstream.toXML(in));
72: TypeWithEnums out = (TypeWithEnums) xstream
73: .fromXML(expectedXml);
74: assertSame(out.poly, PolymorphicEnum.B);
75: assertSame(out.simple, SimpleEnum.GREEN);
76: }
77:
78: public void testEnumsAreImmutable() {
79: List in = new ArrayList();
80: in.add(SimpleEnum.GREEN);
81: in.add(SimpleEnum.GREEN);
82: in.add(PolymorphicEnum.A);
83: in.add(PolymorphicEnum.A);
84: String expectedXml = "" + "<list>\n"
85: + " <simple>GREEN</simple>\n"
86: + " <simple>GREEN</simple>\n"
87: + " <polymorphic>A</polymorphic>\n"
88: + " <polymorphic>A</polymorphic>\n" + "</list>";
89: assertEquals(expectedXml, xstream.toXML(in));
90: assertEquals(in, xstream.fromXML(expectedXml));
91: }
92: }
|