ConstructorTest.java revision 5d709784bbf5001012d7f25172927d46f6c1abe1
1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package tests.api.java.lang.reflect;
19
20import dalvik.annotation.TestLevel;
21import dalvik.annotation.TestTargetNew;
22import dalvik.annotation.TestTargetClass;
23
24import java.lang.annotation.Annotation;
25import java.lang.annotation.ElementType;
26import java.lang.annotation.Retention;
27import java.lang.annotation.RetentionPolicy;
28import java.lang.annotation.Target;
29import java.lang.reflect.Constructor;
30import java.lang.reflect.Modifier;
31import java.lang.reflect.Type;
32import java.lang.reflect.TypeVariable;
33import java.util.Arrays;
34import java.util.HashSet;
35import java.util.Set;
36
37@TestTargetClass(
38        value = Constructor.class,
39        untestedMethods = {
40            @TestTargetNew(
41               level = TestLevel.NOT_FEASIBLE,
42               method = "isSynthetic",
43               args = {},
44               notes =  "Since code which relies on synthetic members is not " +
45               "portable, this should not be tested"
46            )
47        })
48public class ConstructorTest extends junit.framework.TestCase {
49
50
51    @Retention(RetentionPolicy.RUNTIME)
52    @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER})
53    static @interface ConstructorTestAnnotationRuntime0 {
54    }
55
56    @Retention(RetentionPolicy.RUNTIME)
57    @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER})
58    static @interface ConstructorTestAnnotationRuntime1 {
59    }
60
61    @Retention(RetentionPolicy.CLASS)
62    @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER})
63    static @interface ConstructorTestAnnotationClass0 {
64    }
65
66    @Retention(RetentionPolicy.SOURCE)
67    @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER})
68    static @interface ConstructorTestAnnotationSource0 {
69    }
70
71    static class ConstructorTestHelper extends Object {
72        int cval;
73
74        @ConstructorTestAnnotationRuntime0
75        @ConstructorTestAnnotationRuntime1
76        @ConstructorTestAnnotationClass0
77        @ConstructorTestAnnotationSource0
78        public ConstructorTestHelper() throws IndexOutOfBoundsException {
79            cval = 99;
80        }
81
82        public ConstructorTestHelper(
83                @ConstructorTestAnnotationRuntime0
84                @ConstructorTestAnnotationRuntime1
85                @ConstructorTestAnnotationClass0
86                @ConstructorTestAnnotationSource0 Object x) {
87        }
88
89        public ConstructorTestHelper(String... x) {
90        }
91
92        private ConstructorTestHelper(int a) {
93        }
94
95        protected ConstructorTestHelper(long a) {
96        }
97
98        public int check() {
99            return cval;
100        }
101    }
102
103    static class GenericConstructorTestHelper<T, S extends T, E extends Exception> {
104        public GenericConstructorTestHelper(T t, S s) {}
105        public GenericConstructorTestHelper() throws E{}
106    }
107
108//    Used to test synthetic constructor.
109//
110//    static class Outer {
111//        private Outer(){}
112//        class Inner {
113//            {new Outer();}
114//        }
115//    }
116
117    /**
118     * @tests java.lang.reflect.Constructor#getDeclaredAnnotations()
119     */
120    @TestTargetNew(
121        level = TestLevel.COMPLETE,
122        notes = "",
123        method = "getParameterAnnotations",
124        args = {}
125    )
126    public void test_getParameterAnnotations() throws Exception {
127        Constructor<ConstructorTestHelper> ctor1 = ConstructorTestHelper.class
128                .getConstructor(Object.class);
129        Annotation[][] paramAnnotations = ctor1.getParameterAnnotations();
130        assertEquals("Annotations for wrong number of parameters returned", 1,
131                paramAnnotations.length);
132        assertEquals("Wrong number of annotations returned", 2,
133                paramAnnotations[0].length);
134
135        Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
136        ignoreOrder.add(paramAnnotations[0][0].annotationType());
137        ignoreOrder.add(paramAnnotations[0][1].annotationType());
138
139        assertTrue("Missing ConstructorTestAnnotationRuntime0", ignoreOrder
140                .contains(ConstructorTestAnnotationRuntime0.class));
141        assertTrue("Missing ConstructorTestAnnotationRuntime1", ignoreOrder
142                .contains(ConstructorTestAnnotationRuntime1.class));
143    }
144
145
146    /**
147     * @tests java.lang.reflect.Constructor#getDeclaredAnnotations()
148     */
149    @TestTargetNew(
150        level = TestLevel.COMPLETE,
151        notes = "",
152        method = "getDeclaredAnnotations",
153        args = {}
154    )
155    public void test_getDeclaredAnnotations() throws Exception {
156        Constructor<ConstructorTestHelper> ctor1 = null;
157        ctor1 = ConstructorTestHelper.class.getConstructor(new Class[0]);
158        Annotation[] annotations = ctor1.getDeclaredAnnotations();
159        assertEquals("Wrong number of annotations returned", 2,
160                annotations.length);
161        Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
162        ignoreOrder.add(annotations[0].annotationType());
163        ignoreOrder.add(annotations[1].annotationType());
164
165        assertTrue("Missing ConstructorTestAnnotationRuntime0", ignoreOrder
166                .contains(ConstructorTestAnnotationRuntime0.class));
167        assertTrue("Missing ConstructorTestAnnotationRuntime1", ignoreOrder
168                .contains(ConstructorTestAnnotationRuntime1.class));
169    }
170
171    /**
172     * @tests java.lang.reflect.Constructor#isVarargs()
173     */
174    @TestTargetNew(
175        level = TestLevel.COMPLETE,
176        notes = "",
177        method = "isVarArgs",
178        args = {}
179    )
180    public void test_isVarArgs() throws Exception {
181        Constructor<ConstructorTestHelper> varArgCtor = ConstructorTestHelper.class
182                .getConstructor(String[].class);
183        assertTrue("Vararg constructor not recognized", varArgCtor.isVarArgs());
184
185        Constructor<ConstructorTestHelper> nonVarArgCtor = ConstructorTestHelper.class
186                .getConstructor(Object.class);
187        assertFalse("Non vararg constructor recognized as vararg constructor",
188                nonVarArgCtor.isVarArgs());
189    }
190
191    /**
192     * @tests java.lang.reflect.Constructor#hashCode()
193     */
194    @TestTargetNew(
195        level = TestLevel.COMPLETE,
196        notes = "",
197        method = "hashCode",
198        args = {}
199    )
200    public void test_hashCode() throws Exception {
201        Constructor<ConstructorTestHelper> constructor = ConstructorTestHelper.class
202                .getConstructor();
203        assertEquals(
204                "The constructor's hashCode is not equal to the hashCode of the name of the declaring class",
205                ConstructorTestHelper.class.getName().hashCode(), constructor
206                        .hashCode());
207    }
208
209    /**
210     * @tests java.lang.reflect.Constructor#toGenericString()
211     */
212    @SuppressWarnings("unchecked")
213    @TestTargetNew(
214        level = TestLevel.COMPLETE,
215        notes = "",
216        method = "toGenericString",
217        args = {}
218    )
219    public void test_toGenericString() throws Exception {
220        Constructor<GenericConstructorTestHelper> genericCtor = GenericConstructorTestHelper.class
221                .getConstructor(Object.class, Object.class);
222        assertEquals(
223                "Wrong generic string returned",
224                "public tests.api.java.lang.reflect.ConstructorTest$GenericConstructorTestHelper(T,S)",
225                genericCtor.toGenericString());
226        Constructor<GenericConstructorTestHelper> ctor = GenericConstructorTestHelper.class
227                .getConstructor();
228        assertEquals(
229                "Wrong generic string returned",
230                "public tests.api.java.lang.reflect.ConstructorTest$GenericConstructorTestHelper() throws E",
231                ctor.toGenericString());
232    }
233
234 /**
235     * @tests java.lang.reflect.Constructor#equals(java.lang.Object)
236     */
237    @TestTargetNew(
238        level = TestLevel.COMPLETE,
239        notes = "",
240        method = "equals",
241        args = {java.lang.Object.class}
242    )
243    public void test_equalsLjava_lang_Object() {
244        Constructor<ConstructorTestHelper> ctor1 = null, ctor2 = null;
245        try {
246            ctor1 = ConstructorTestHelper.class.getConstructor(
247                    new Class[0]);
248            ctor2 = ConstructorTestHelper.class.getConstructor(Object.class);
249        } catch (Exception e) {
250            fail("Exception during equals test : " + e.getMessage());
251        }
252        assertTrue("Different Contructors returned equal", !ctor1.equals(ctor2));
253    }
254
255    /**
256     * @tests java.lang.reflect.Constructor#getDeclaringClass()
257     */
258    @TestTargetNew(
259        level = TestLevel.COMPLETE,
260        notes = "",
261        method = "getDeclaringClass",
262        args = {}
263    )
264    public void test_getDeclaringClass() {
265        boolean val = false;
266        try {
267            Class<? extends ConstructorTestHelper> pclass = new ConstructorTestHelper().getClass();
268            Constructor<? extends ConstructorTestHelper> ctor = pclass.getConstructor(new Class[0]);
269            val = ctor.getDeclaringClass().equals(pclass);
270        } catch (Exception e) {
271            fail("Exception during test : " + e.getMessage());
272        }
273        assertTrue("Returned incorrect declaring class", val);
274    }
275
276    /**
277     * @tests java.lang.reflect.Constructor#getExceptionTypes()
278     */
279    @TestTargetNew(
280        level = TestLevel.COMPLETE,
281        notes = "",
282        method = "getExceptionTypes",
283        args = {}
284    )
285    public void test_getExceptionTypes() {
286        // Test for method java.lang.Class []
287        // java.lang.reflect.Constructor.getExceptionTypes()
288        Class[] exceptions = null;
289        Class<? extends IndexOutOfBoundsException> ex = null;
290        try {
291            Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
292                    .getConstructor(new Class[0]);
293            exceptions = ctor.getExceptionTypes();
294            ex = new IndexOutOfBoundsException().getClass();
295        } catch (Exception e) {
296            fail("Exception during test : " + e.getMessage());
297        }
298        assertEquals("Returned exception list of incorrect length",
299                1, exceptions.length);
300        assertTrue("Returned incorrect exception", exceptions[0].equals(ex));
301    }
302
303    /**
304     * @tests java.lang.reflect.Constructor#getModifiers()
305     */
306    @TestTargetNew(
307        level = TestLevel.COMPLETE,
308        notes = "",
309        method = "getModifiers",
310        args = {}
311    )
312    public void test_getModifiers() {
313        // Test for method int java.lang.reflect.Constructor.getModifiers()
314        int mod = 0;
315        try {
316            Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
317                    .getConstructor(new Class[0]);
318            mod = ctor.getModifiers();
319            assertTrue("Returned incorrect modifers for public ctor",
320                    ((mod & Modifier.PUBLIC) == Modifier.PUBLIC)
321                            && ((mod & Modifier.PRIVATE) == 0));
322        } catch (NoSuchMethodException e) {
323            fail("Exception during test : " + e.getMessage());
324        }
325        try {
326            Class[] cl = { int.class };
327            Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
328                    .getDeclaredConstructor(cl);
329            mod = ctor.getModifiers();
330            assertTrue("Returned incorrect modifers for private ctor",
331                    ((mod & Modifier.PRIVATE) == Modifier.PRIVATE)
332                            && ((mod & Modifier.PUBLIC) == 0));
333        } catch (NoSuchMethodException e) {
334            fail("Exception during test : " + e.getMessage());
335        }
336        try {
337            Class[] cl = { long.class };
338            Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
339                    .getDeclaredConstructor(cl);
340            mod = ctor.getModifiers();
341            assertTrue("Returned incorrect modifers for private ctor",
342                    ((mod & Modifier.PROTECTED) == Modifier.PROTECTED)
343                            && ((mod & Modifier.PUBLIC) == 0));
344        } catch (NoSuchMethodException e) {
345            fail("NoSuchMethodException during test : " + e.getMessage());
346        }
347    }
348
349    /**
350     * @tests java.lang.reflect.Constructor#getName()
351     */
352    @TestTargetNew(
353        level = TestLevel.COMPLETE,
354        notes = "",
355        method = "getName",
356        args = {}
357    )
358    public void test_getName() {
359        // Test for method java.lang.String
360        // java.lang.reflect.Constructor.getName()
361        try {
362            Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
363                    .getConstructor(new Class[0]);
364            assertTrue(
365                    "Returned incorrect name: " + ctor.getName(),
366                    ctor
367                            .getName()
368                            .equals(
369                                    "tests.api.java.lang.reflect.ConstructorTest$ConstructorTestHelper"));
370        } catch (Exception e) {
371            fail("Exception obtaining contructor : " + e.getMessage());
372        }
373    }
374
375    /**
376     * @tests java.lang.reflect.Constructor#getParameterTypes()
377     */
378    @TestTargetNew(
379        level = TestLevel.COMPLETE,
380        notes = "",
381        method = "getParameterTypes",
382        args = {}
383    )
384    public void test_getParameterTypes() {
385        // Test for method java.lang.Class []
386        // java.lang.reflect.Constructor.getParameterTypes()
387        Class[] types = null;
388        try {
389            Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
390                    .getConstructor(new Class[0]);
391            types = ctor.getParameterTypes();
392        } catch (Exception e) {
393            fail("Exception during getParameterTypes test:"
394                    + e.toString());
395        }
396        assertEquals("Incorrect parameter returned", 0, types.length);
397
398        Class[] parms = null;
399        try {
400            parms = new Class[1];
401            parms[0] = new Object().getClass();
402            Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
403                    .getConstructor(parms);
404            types = ctor.getParameterTypes();
405        } catch (Exception e) {
406            fail("Exception during getParameterTypes test:"
407                    + e.toString());
408        }
409        assertTrue("Incorrect parameter returned", types[0].equals(parms[0]));
410    }
411
412    /**
413     * @tests java.lang.reflect.Constructor#getGenericParameterTypes()
414     */
415    @TestTargetNew(
416        level = TestLevel.COMPLETE,
417        notes = "",
418        method = "getGenericParameterTypes",
419        args = {}
420    )
421    @SuppressWarnings("unchecked")
422    public void test_getGenericParameterTypes() {
423        Type[] types = null;
424        try {
425            Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper()
426                    .getClass().getConstructor(new Class[0]);
427            types = ctor.getGenericParameterTypes();
428        } catch (Exception e) {
429            fail("Exception during getParameterTypes test:" + e.toString());
430        }
431        assertEquals("Incorrect parameter returned", 0, types.length);
432
433        Class<?>[] parms = null;
434        try {
435            parms = new Class[] {Object.class};
436            Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper()
437                    .getClass().getConstructor(parms);
438            types = ctor.getGenericParameterTypes();
439        } catch (Exception e) {
440            fail("Exception during getParameterTypes test:" + e.toString());
441        }
442        assertTrue("Incorrect parameter returned", types[0].equals(parms[0]));
443
444
445        try {
446            Constructor<GenericConstructorTestHelper> constructor = GenericConstructorTestHelper.class
447                    .getConstructor(Object.class, Object.class);
448            types = constructor.getGenericParameterTypes();
449        } catch (Exception e) {
450            fail("Exception during getParameterTypes test:" + e.toString());
451        }
452
453        assertEquals("Wrong number of parameter types returned", 2,
454                types.length);
455
456        assertEquals("Wrong number of parameter types returned", "T",
457                ((TypeVariable)types[0]).getName());
458        assertEquals("Wrong number of parameter types returned", "S",
459                ((TypeVariable)types[1]).getName());
460    }
461
462    /**
463     * @tests java.lang.reflect.Constructor#getGenericParameterTypes()
464     */
465    @TestTargetNew(
466        level = TestLevel.COMPLETE,
467        notes = "",
468        method = "getGenericExceptionTypes",
469        args = {}
470    )
471    @SuppressWarnings("unchecked")
472    public void test_getGenericExceptionTypes() {
473        Type[] types = null;
474
475        try {
476            Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper()
477                    .getClass().getConstructor(new Class[0]);
478            types = ctor.getGenericExceptionTypes();
479        } catch (Exception e) {
480            fail("Exception during getGenericExceptionTypes test:" + e.toString());
481        }
482        System.out.println(Arrays.toString(types));
483        assertEquals("Wrong number of exception types returned", 1, types.length);
484
485
486        try {
487            Constructor<GenericConstructorTestHelper> constructor = GenericConstructorTestHelper.class
488                    .getConstructor();
489            types = constructor.getGenericExceptionTypes();
490        } catch (Exception e) {
491            fail("Exception during getGenericExceptionTypes test:"
492                    + e.toString());
493        }
494
495        assertEquals("Wrong number of exception types returned", 1,
496                types.length);
497
498        assertEquals("Wrong exception name returned.", "E",
499                ((TypeVariable)types[0]).getName());
500
501    }
502
503
504
505    /**
506     * @tests java.lang.reflect.Constructor#newInstance(java.lang.Object[])
507     */
508    @TestTargetNew(
509        level = TestLevel.COMPLETE,
510        notes = "",
511        method = "newInstance",
512        args = {java.lang.Object[].class}
513    )
514    public void test_newInstance$Ljava_lang_Object() {
515        // Test for method java.lang.Object
516        // java.lang.reflect.Constructor.newInstance(java.lang.Object [])
517
518        ConstructorTestHelper test = null;
519        try {
520            Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
521                    .getConstructor(new Class[0]);
522            test = ctor.newInstance((Object[])null);
523        } catch (Exception e) {
524            fail("Failed to create instance : " + e.getMessage());
525        }
526        assertEquals("improper instance created", 99, test.check());
527    }
528
529    /**
530     * @tests java.lang.reflect.Constructor#toString()
531     */
532    @TestTargetNew(
533        level = TestLevel.COMPLETE,
534        notes = "",
535        method = "toString",
536        args = {}
537    )
538    public void test_toString() {
539        // Test for method java.lang.String
540        // java.lang.reflect.Constructor.toString()
541        Class[] parms = null;
542        Constructor<? extends ConstructorTestHelper> ctor = null;
543        try {
544            parms = new Class[1];
545            parms[0] = new Object().getClass();
546            ctor = new ConstructorTestHelper().getClass().getConstructor(parms);
547        } catch (Exception e) {
548            fail("Exception during getParameterTypes test:"
549                    + e.toString());
550        }
551        assertTrue(
552                "Returned incorrect string representation: " + ctor.toString(),
553                ctor
554                        .toString()
555                        .equals(
556                                "public tests.api.java.lang.reflect.ConstructorTest$ConstructorTestHelper(java.lang.Object)"));
557    }
558
559    /**
560     * Sets up the fixture, for example, open a network connection. This method
561     * is called before a test is executed.
562     */
563    protected void setUp() {
564    }
565
566    /**
567     * Tears down the fixture, for example, close a network connection. This
568     * method is called after a test is executed.
569     */
570    protected void tearDown() {
571    }
572}
573
574