View Javadoc

1   /**
2    * Copyright (c) 2008-2011, 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  
17  package org.yaml.snakeyaml.issues.issue114;
18  
19  import java.util.LinkedHashMap;
20  import java.util.LinkedList;
21  import java.util.List;
22  import java.util.Map;
23  
24  import junit.framework.TestCase;
25  
26  import org.yaml.snakeyaml.Yaml;
27  
28  public class PreserveTypeTest extends TestCase {
29  
30      public static class MyBean {
31  
32          private int dummy;
33  
34          public int getDummy() {
35              return dummy;
36          }
37  
38          public void setDummy(int dummy) {
39              this.dummy = dummy;
40          }
41      }
42  
43      public static class ReferencingBean {
44  
45          private List<MyBean> myBeans = new LinkedList<PreserveTypeTest.MyBean>();
46  
47          public List<MyBean> getMyBeans() {
48              return myBeans;
49          }
50  
51          public void setMyBeans(List<MyBean> myBeans) {
52              this.myBeans = myBeans;
53          }
54      }
55  
56      private Map<String, Object> createData(boolean collectionFirst) {
57          MyBean myBean = new MyBean();
58          ReferencingBean referencingBean = new ReferencingBean();
59          referencingBean.getMyBeans().add(myBean);
60  
61          LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
62          if (collectionFirst) {
63              map.put("referencingBean", referencingBean);
64              map.put("myBean", myBean);
65          } else {
66              map.put("myBean", myBean);
67              map.put("referencingBean", referencingBean);
68          }
69          return map;
70      }
71  
72      private void check(String doc) {
73          Yaml yaml = new Yaml();
74          @SuppressWarnings("unchecked")
75          Map<String, Object> loaded = (Map<String, Object>) yaml.load(doc);
76          Object myBean2 = loaded.get("myBean");
77          assertTrue(myBean2.getClass().toString(), myBean2 instanceof MyBean);
78      }
79  
80      public void testPreserveType1() {
81          Yaml yaml = new Yaml();
82          String s = yaml.dump(createData(true));
83          check(s);
84      }
85  
86      public void testPreserveType2() {
87          Yaml yaml = new Yaml();
88          String s = yaml.dump(createData(false));
89          check(s);
90      }
91  }