View Javadoc

1   /**
2    * Copyright (c) 2008-2012, http://www.snakeyaml.org
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.yaml.snakeyaml.issues.issue114;
17  
18  import java.util.LinkedHashMap;
19  import java.util.LinkedList;
20  import java.util.List;
21  import java.util.Map;
22  
23  import junit.framework.TestCase;
24  
25  import org.yaml.snakeyaml.Yaml;
26  
27  public class PreserveTypeTest extends TestCase {
28  
29      public static class MyBean {
30  
31          private int dummy;
32  
33          public int getDummy() {
34              return dummy;
35          }
36  
37          public void setDummy(int dummy) {
38              this.dummy = dummy;
39          }
40      }
41  
42      public static class ReferencingBean {
43  
44          private List<MyBean> myBeans = new LinkedList<PreserveTypeTest.MyBean>();
45  
46          public List<MyBean> getMyBeans() {
47              return myBeans;
48          }
49  
50          public void setMyBeans(List<MyBean> myBeans) {
51              this.myBeans = myBeans;
52          }
53      }
54  
55      private Map<String, Object> createData(boolean collectionFirst) {
56          MyBean myBean = new MyBean();
57          ReferencingBean referencingBean = new ReferencingBean();
58          referencingBean.getMyBeans().add(myBean);
59  
60          LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
61          if (collectionFirst) {
62              map.put("referencingBean", referencingBean);
63              map.put("myBean", myBean);
64          } else {
65              map.put("myBean", myBean);
66              map.put("referencingBean", referencingBean);
67          }
68          return map;
69      }
70  
71      private void check(String doc) {
72          Yaml yaml = new Yaml();
73          @SuppressWarnings("unchecked")
74          Map<String, Object> loaded = (Map<String, Object>) yaml.load(doc);
75          Object myBean2 = loaded.get("myBean");
76          assertTrue(myBean2.getClass().toString(), myBean2 instanceof MyBean);
77      }
78  
79      public void testPreserveType1() {
80          Yaml yaml = new Yaml();
81          String s = yaml.dump(createData(true));
82          check(s);
83      }
84  
85      public void testPreserveType2() {
86          Yaml yaml = new Yaml();
87          String s = yaml.dump(createData(false));
88          check(s);
89      }
90  }