View Javadoc
1   /*
2    * Copyright (C) 2008 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  
17  package com.google.common.collect.testing.testers;
18  
19  import com.google.common.annotations.GwtCompatible;
20  import com.google.common.collect.testing.AbstractCollectionTester;
21  import com.google.common.collect.testing.Helpers;
22  import java.util.Collection;
23  import java.util.List;
24  
25  /**
26   * Base class for list testers.
27   *
28   * @author George van den Driessche
29   */
30  @GwtCompatible
31  public class AbstractListTester<E> extends AbstractCollectionTester<E> {
32    /*
33     * Previously we had a field named list that was initialized to the value of
34     * collection in setUp(), but that caused problems when a tester changed the
35     * value of list or collection but not both.
36     */
37    protected final List<E> getList() {
38      return (List<E>) collection;
39    }
40  
41    /**
42     * {@inheritDoc}
43     * <p>
44     * The {@code AbstractListTester} implementation overrides
45     * {@link AbstractCollectionTester#expectContents(Collection)} to verify that
46     * the order of the elements in the list under test matches what is expected.
47     */
48    @Override
49    protected void expectContents(Collection<E> expectedCollection) {
50      List<E> expectedList = Helpers.copyToList(expectedCollection);
51      // Avoid expectEquals() here to delay reason manufacture until necessary.
52      if (getList().size() != expectedList.size()) {
53        fail("size mismatch: " + reportContext(expectedList));
54      }
55      for (int i = 0; i < expectedList.size(); i++) {
56        E expected = expectedList.get(i);
57        E actual = getList().get(i);
58        if (expected != actual && (expected == null || !expected.equals(actual))) {
59          fail("mismatch at index " + i + ": " + reportContext(expectedList));
60        }
61      }
62    }
63  
64    /**
65     * Used to delay string formatting until actually required, as it
66     * otherwise shows up in the test execution profile when running an
67     * extremely large numbers of tests.
68     */
69    private String reportContext(List<E> expected) {
70      return Platform.format(
71          "expected collection %s; actual collection %s", expected, this.collection);
72    }
73  }