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.representer;
17  
18  import java.util.Iterator;
19  
20  import junit.framework.TestCase;
21  
22  import org.yaml.snakeyaml.Yaml;
23  
24  /**
25   * Test {@link issue69 http://code.google.com/p/snakeyaml/issues/detail?id=69}
26   */
27  public class RepresentIterableTest extends TestCase {
28  
29      public void testIterable() {
30          Yaml yaml = new Yaml();
31          try {
32              yaml.dump(new CounterFactory());
33              fail("Iterable should not be treated as sequence by default.");
34          } catch (Exception e) {
35              assertEquals(
36                      "No JavaBean properties found in org.yaml.snakeyaml.representer.RepresentIterableTest$CounterFactory",
37                      e.getMessage());
38          }
39      }
40  
41      public void testIterator() {
42          Yaml yaml = new Yaml();
43          String output = yaml.dump(new Counter(7));
44          assertEquals("[0, 1, 2, 3, 4, 5, 6]\n", output);
45      }
46  
47      private class CounterFactory implements Iterable<Integer> {
48          public Iterator<Integer> iterator() {
49              return new Counter(10);
50          }
51      }
52  
53      private class Counter implements Iterator<Integer> {
54          private int max = 0;
55          private int counter = 0;
56  
57          public Counter(int max) {
58              this.max = max;
59          }
60  
61          public boolean hasNext() {
62              return counter < max;
63          }
64  
65          public Integer next() {
66              return counter++;
67          }
68  
69          public void remove() {
70              throw new UnsupportedOperationException();
71          }
72      }
73  }