UnmodifiableListIteratorTest.java revision 1d580d0f6ee4f21eb309ba7b509d2c6d671c4044
1/*
2 * Copyright (C) 2010 The Guava Authors
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
17package com.google.common.collect;
18
19import com.google.common.annotations.GwtCompatible;
20
21import junit.framework.TestCase;
22
23import java.util.Iterator;
24import java.util.ListIterator;
25import java.util.NoSuchElementException;
26
27/**
28 * Tests for UnmodifiableListIterator.
29 *
30 * @author Louis Wasserman
31 */
32@GwtCompatible
33public class UnmodifiableListIteratorTest extends TestCase {
34  public void testRemove() {
35    Iterator<String> iterator = create();
36
37    assertTrue(iterator.hasNext());
38    assertEquals("a", iterator.next());
39    try {
40      iterator.remove();
41      fail();
42    } catch (UnsupportedOperationException expected) {}
43  }
44
45  public void testAdd() {
46    ListIterator<String> iterator = create();
47
48    assertTrue(iterator.hasNext());
49    assertEquals("a", iterator.next());
50    assertEquals("b", iterator.next());
51    assertEquals("b", iterator.previous());
52    try {
53      iterator.add("c");
54      fail();
55    } catch (UnsupportedOperationException expected) {}
56  }
57
58  public void testSet() {
59    ListIterator<String> iterator = create();
60
61    assertTrue(iterator.hasNext());
62    assertEquals("a", iterator.next());
63    assertEquals("b", iterator.next());
64    assertEquals("b", iterator.previous());
65    try {
66      iterator.set("c");
67      fail();
68    } catch (UnsupportedOperationException expected) {}
69  }
70
71  UnmodifiableListIterator<String> create() {
72    final String[] array = {"a", "b", "c"};
73
74    return new UnmodifiableListIterator<String>() {
75      int i;
76      @Override
77      public boolean hasNext() {
78        return i < array.length;
79      }
80      @Override
81      public String next() {
82        if (!hasNext()) {
83          throw new NoSuchElementException();
84        }
85        return array[i++];
86      }
87      @Override public boolean hasPrevious() {
88        return i > 0;
89      }
90      @Override public int nextIndex() {
91        return i;
92      }
93      @Override public String previous() {
94        if(!hasPrevious())
95          throw new NoSuchElementException();
96        return array[--i];
97      }
98      @Override public int previousIndex() {
99        return i-1;
100      }
101    };
102  }
103}
104