001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect.testing.testers;
018
019import static com.google.common.collect.testing.Helpers.assertEqualIgnoringOrder;
020import static com.google.common.collect.testing.Helpers.getMethod;
021import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER;
022import static com.google.common.collect.testing.features.CollectionSize.ZERO;
023import static com.google.common.collect.testing.testers.ReflectionFreeAssertThrows.assertThrows;
024import static java.util.Arrays.asList;
025
026import com.google.common.annotations.GwtCompatible;
027import com.google.common.annotations.GwtIncompatible;
028import com.google.common.annotations.J2ktIncompatible;
029import com.google.common.collect.testing.AbstractCollectionTester;
030import com.google.common.collect.testing.WrongType;
031import com.google.common.collect.testing.features.CollectionFeature;
032import com.google.common.collect.testing.features.CollectionSize;
033import java.lang.reflect.Method;
034import java.util.Arrays;
035import java.util.Collection;
036import java.util.List;
037import org.junit.Ignore;
038
039/**
040 * A generic JUnit test which tests {@code toArray()} operations on a collection. Can't be invoked
041 * directly; please see {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
042 *
043 * @author Kevin Bourrillion
044 * @author Chris Povirk
045 */
046@GwtCompatible(emulated = true)
047@Ignore("test runners must not instantiate and run this directly, only via suites we build")
048// @Ignore affects the Android test runner, which respects JUnit 4 annotations on JUnit 3 tests.
049@SuppressWarnings("JUnit4ClassUsedInJUnit3")
050public class CollectionToArrayTester<E> extends AbstractCollectionTester<E> {
051  public void testToArray_noArgs() {
052    Object[] array = collection.toArray();
053    expectArrayContentsAnyOrder(createSamplesArray(), array);
054  }
055
056  /**
057   * {@link Collection#toArray(Object[])} says: "Note that {@code toArray(new Object[0])} is
058   * identical in function to {@code toArray()}."
059   *
060   * <p>For maximum effect, the collection under test should be created from an element array of a
061   * type other than {@code Object[]}.
062   */
063  public void testToArray_isPlainObjectArray() {
064    Object[] array = collection.toArray();
065    assertEquals(Object[].class, array.getClass());
066  }
067
068  public void testToArray_emptyArray() {
069    E[] empty = getSubjectGenerator().createArray(0);
070    E[] array = collection.toArray(empty);
071    assertEquals(
072        "toArray(emptyT[]) should return an array of type T", empty.getClass(), array.getClass());
073    assertEquals("toArray(emptyT[]).length:", getNumElements(), array.length);
074    expectArrayContentsAnyOrder(createSamplesArray(), array);
075  }
076
077  @CollectionFeature.Require(KNOWN_ORDER)
078  public void testToArray_emptyArray_ordered() {
079    E[] empty = getSubjectGenerator().createArray(0);
080    E[] array = collection.toArray(empty);
081    assertEquals(
082        "toArray(emptyT[]) should return an array of type T", empty.getClass(), array.getClass());
083    assertEquals("toArray(emptyT[]).length:", getNumElements(), array.length);
084    expectArrayContentsInOrder(getOrderedElements(), array);
085  }
086
087  public void testToArray_emptyArrayOfObject() {
088    Object[] in = new Object[0];
089    Object[] array = collection.toArray(in);
090    assertEquals(
091        "toArray(emptyObject[]) should return an array of type Object",
092        Object[].class,
093        array.getClass());
094    assertEquals("toArray(emptyObject[]).length", getNumElements(), array.length);
095    expectArrayContentsAnyOrder(createSamplesArray(), array);
096  }
097
098  public void testToArray_rightSizedArray() {
099    E[] array = getSubjectGenerator().createArray(getNumElements());
100    assertSame(
101        "toArray(sameSizeE[]) should return the given array", array, collection.toArray(array));
102    expectArrayContentsAnyOrder(createSamplesArray(), array);
103  }
104
105  @CollectionFeature.Require(KNOWN_ORDER)
106  public void testToArray_rightSizedArray_ordered() {
107    E[] array = getSubjectGenerator().createArray(getNumElements());
108    assertSame(
109        "toArray(sameSizeE[]) should return the given array", array, collection.toArray(array));
110    expectArrayContentsInOrder(getOrderedElements(), array);
111  }
112
113  public void testToArray_rightSizedArrayOfObject() {
114    Object[] array = new Object[getNumElements()];
115    assertSame(
116        "toArray(sameSizeObject[]) should return the given array",
117        array,
118        collection.toArray(array));
119    expectArrayContentsAnyOrder(createSamplesArray(), array);
120  }
121
122  @CollectionFeature.Require(KNOWN_ORDER)
123  public void testToArray_rightSizedArrayOfObject_ordered() {
124    Object[] array = new Object[getNumElements()];
125    assertSame(
126        "toArray(sameSizeObject[]) should return the given array",
127        array,
128        collection.toArray(array));
129    expectArrayContentsInOrder(getOrderedElements(), array);
130  }
131
132  public void testToArray_oversizedArray() {
133    E[] array = getSubjectGenerator().createArray(getNumElements() + 2);
134    array[getNumElements()] = e3();
135    array[getNumElements() + 1] = e3();
136    assertSame(
137        "toArray(overSizedE[]) should return the given array", array, collection.toArray(array));
138
139    List<E> subArray = asList(array).subList(0, getNumElements());
140    E[] expectedSubArray = createSamplesArray();
141    for (int i = 0; i < getNumElements(); i++) {
142      assertTrue(
143          "toArray(overSizedE[]) should contain element " + expectedSubArray[i],
144          subArray.contains(expectedSubArray[i]));
145    }
146    assertNull(
147        "The array element immediately following the end of the collection should be nulled",
148        array[getNumElements()]);
149    // array[getNumElements() + 1] might or might not have been nulled
150  }
151
152  @CollectionFeature.Require(KNOWN_ORDER)
153  public void testToArray_oversizedArray_ordered() {
154    E[] array = getSubjectGenerator().createArray(getNumElements() + 2);
155    array[getNumElements()] = e3();
156    array[getNumElements() + 1] = e3();
157    assertSame(
158        "toArray(overSizedE[]) should return the given array", array, collection.toArray(array));
159
160    List<E> expected = getOrderedElements();
161    for (int i = 0; i < getNumElements(); i++) {
162      assertEquals(expected.get(i), array[i]);
163    }
164    assertNull(
165        "The array element immediately following the end of the collection should be nulled",
166        array[getNumElements()]);
167    // array[getNumElements() + 1] might or might not have been nulled
168  }
169
170  @CollectionSize.Require(absent = ZERO)
171  public void testToArray_emptyArrayOfWrongTypeForNonEmptyCollection() {
172    assertThrows(
173        ArrayStoreException.class,
174        () -> {
175          WrongType[] array = new WrongType[0];
176          collection.toArray(array);
177        });
178  }
179
180  @CollectionSize.Require(ZERO)
181  public void testToArray_emptyArrayOfWrongTypeForEmptyCollection() {
182    WrongType[] array = new WrongType[0];
183    assertSame(
184        "toArray(sameSizeNotAssignableTo[]) should return the given array",
185        array,
186        collection.toArray(array));
187  }
188
189  private void expectArrayContentsAnyOrder(Object[] expected, Object[] actual) {
190    assertEqualIgnoringOrder(asList(expected), asList(actual));
191  }
192
193  private void expectArrayContentsInOrder(List<E> expected, Object[] actual) {
194    assertEquals("toArray() ordered contents: ", expected, asList(actual));
195  }
196
197  /**
198   * Returns the {@link Method} instance for {@link #testToArray_isPlainObjectArray()} so that tests
199   * of {@link Arrays#asList(Object[])} can suppress it with {@code
200   * FeatureSpecificTestSuiteBuilder.suppressing()} until <a
201   * href="https://bugs.openjdk.org/browse/JDK-6260652">JDK-6260652</a> is fixed.
202   */
203  @J2ktIncompatible
204  @GwtIncompatible // reflection
205  public static Method getToArrayIsPlainObjectArrayMethod() {
206    return getMethod(CollectionToArrayTester.class, "testToArray_isPlainObjectArray");
207  }
208}