guava
261 строка · 8.7 Кб
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
17package com.google.common.collect.testing;
18
19import com.google.common.annotations.GwtCompatible;
20import com.google.errorprone.annotations.CanIgnoreReturnValue;
21import com.google.errorprone.annotations.OverridingMethodsMustInvokeSuper;
22import java.util.ArrayList;
23import java.util.Arrays;
24import java.util.Collection;
25import java.util.Collections;
26import java.util.List;
27import org.checkerframework.checker.nullness.qual.Nullable;
28import org.junit.Ignore;
29
30/**
31* Base class for testers of classes (including {@link Collection} and {@link java.util.Map Map})
32* that contain elements.
33*
34* @param <C> the type of the container
35* @param <E> the type of the container's contents
36* @author George van den Driessche
37*/
38@GwtCompatible
39@Ignore // Affects only Android test runner, which respects JUnit 4 annotations on JUnit 3 tests.
40@ElementTypesAreNonnullByDefault
41public abstract class AbstractContainerTester<C, E extends @Nullable Object>
42extends AbstractTester<OneSizeTestContainerGenerator<C, E>> {
43protected SampleElements<E> samples;
44protected C container;
45
46@Override
47@OverridingMethodsMustInvokeSuper
48public void setUp() throws Exception {
49super.setUp();
50samples = this.getSubjectGenerator().samples();
51resetContainer();
52}
53
54/**
55* @return the contents of the container under test, for use by {@link #expectContents(Object[])
56* expectContents(E...)} and its friends.
57*/
58protected abstract Collection<E> actualContents();
59
60/**
61* Replaces the existing container under test with a new container created by the subject
62* generator.
63*
64* @see #resetContainer(Object) resetContainer(C)
65* @return the new container instance.
66*/
67@CanIgnoreReturnValue
68protected C resetContainer() {
69return resetContainer(getSubjectGenerator().createTestSubject());
70}
71
72/**
73* Replaces the existing container under test with a new container. This is useful when a single
74* test method needs to create multiple containers while retaining the ability to use {@link
75* #expectContents(Object[]) expectContents(E...)} and other convenience methods. The creation of
76* multiple containers in a single method is discouraged in most cases, but it is vital to the
77* iterator tests.
78*
79* @return the new container instance
80* @param newValue the new container instance
81*/
82@CanIgnoreReturnValue
83protected C resetContainer(C newValue) {
84container = newValue;
85return container;
86}
87
88/**
89* @see #expectContents(java.util.Collection)
90* @param elements expected contents of {@link #container}
91*/
92protected final void expectContents(E... elements) {
93expectContents(Arrays.asList(elements));
94}
95
96/**
97* Asserts that the collection under test contains exactly the given elements, respecting
98* cardinality but not order. Subclasses may override this method to provide stronger assertions,
99* e.g., to check ordering in lists, but realize that <strong>unless a test extends {@link
100* com.google.common.collect.testing.testers.AbstractListTester AbstractListTester}, a call to
101* {@code expectContents()} invokes this version</strong>.
102*
103* @param expected expected value of {@link #container}
104*/
105/*
106* TODO: improve this and other implementations and move out of this framework
107* for wider use
108*
109* TODO: could we incorporate the overriding logic from AbstractListTester, by
110* examining whether the features include KNOWN_ORDER?
111*/
112protected void expectContents(Collection<E> expected) {
113Helpers.assertEqualIgnoringOrder(expected, actualContents());
114}
115
116protected void expectUnchanged() {
117expectContents(getOrderedElements());
118}
119
120/**
121* Asserts that the collection under test contains exactly the elements it was initialized with
122* plus the given elements, according to {@link #expectContents(java.util.Collection)}. In other
123* words, for the default {@code expectContents()} implementation, the number of occurrences of
124* each given element has increased by one since the test collection was created, and the number
125* of occurrences of all other elements has not changed.
126*
127* <p>Note: This means that a test like the following will fail if {@code collection} is a {@code
128* Set}:
129*
130* <pre>
131* collection.add(existingElement);
132* expectAdded(existingElement);</pre>
133*
134* <p>In this case, {@code collection} was not modified as a result of the {@code add()} call, and
135* the test will fail because the number of occurrences of {@code existingElement} is unchanged.
136*
137* @param elements expected additional contents of {@link #container}
138*/
139protected final void expectAdded(E... elements) {
140List<E> expected = Helpers.copyToList(getSampleElements());
141expected.addAll(Arrays.asList(elements));
142expectContents(expected);
143}
144
145protected final void expectAdded(int index, E... elements) {
146expectAdded(index, Arrays.asList(elements));
147}
148
149protected final void expectAdded(int index, Collection<E> elements) {
150List<E> expected = Helpers.copyToList(getSampleElements());
151expected.addAll(index, elements);
152expectContents(expected);
153}
154
155/*
156* TODO: if we're testing a list, we could check indexOf(). (Doing it in
157* AbstractListTester isn't enough because many tests that run on lists don't
158* extends AbstractListTester.) We could also iterate over all elements to
159* verify absence
160*/
161protected void expectMissing(E... elements) {
162for (E element : elements) {
163assertFalse("Should not contain " + element, actualContents().contains(element));
164}
165}
166
167protected E[] createSamplesArray() {
168E[] array = getSubjectGenerator().createArray(getNumElements());
169getSampleElements().toArray(array);
170return array;
171}
172
173protected E[] createOrderedArray() {
174E[] array = getSubjectGenerator().createArray(getNumElements());
175getOrderedElements().toArray(array);
176return array;
177}
178
179public static class ArrayWithDuplicate<E extends @Nullable Object> {
180public final E[] elements;
181public final E duplicate;
182
183private ArrayWithDuplicate(E[] elements, E duplicate) {
184this.elements = elements;
185this.duplicate = duplicate;
186}
187}
188
189/**
190* @return an array of the proper size with a duplicate element. The size must be at least three.
191*/
192protected ArrayWithDuplicate<E> createArrayWithDuplicateElement() {
193E[] elements = createSamplesArray();
194E duplicate = elements[(elements.length / 2) - 1];
195elements[(elements.length / 2) + 1] = duplicate;
196return new ArrayWithDuplicate<>(elements, duplicate);
197}
198
199// Helper methods to improve readability of derived classes
200
201protected int getNumElements() {
202return getSubjectGenerator().getCollectionSize().getNumElements();
203}
204
205protected Collection<E> getSampleElements(int howMany) {
206return getSubjectGenerator().getSampleElements(howMany);
207}
208
209protected Collection<E> getSampleElements() {
210return getSampleElements(getNumElements());
211}
212
213/**
214* Returns the {@linkplain #getSampleElements() sample elements} as ordered by {@link
215* TestContainerGenerator#order(List)}. Tests should use this method only if they declare
216* requirement {@link com.google.common.collect.testing.features.CollectionFeature#KNOWN_ORDER}.
217*/
218protected List<E> getOrderedElements() {
219List<E> list = new ArrayList<>();
220for (E e : getSubjectGenerator().order(new ArrayList<E>(getSampleElements()))) {
221list.add(e);
222}
223return Collections.unmodifiableList(list);
224}
225
226/**
227* @return a suitable location for a null element, to use when initializing containers for tests
228* that involve a null element being present.
229*/
230protected int getNullLocation() {
231return getNumElements() / 2;
232}
233
234protected MinimalCollection<E> createDisjointCollection() {
235return MinimalCollection.of(e3(), e4());
236}
237
238protected MinimalCollection<E> emptyCollection() {
239return MinimalCollection.<E>of();
240}
241
242protected final E e0() {
243return samples.e0();
244}
245
246protected final E e1() {
247return samples.e1();
248}
249
250protected final E e2() {
251return samples.e2();
252}
253
254protected final E e3() {
255return samples.e3();
256}
257
258protected final E e4() {
259return samples.e4();
260}
261}
262