1 /* 2 * Copyright (C) 2006 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.reflect; 18 19 import com.google.common.testing.NullPointerTester; 20 import java.lang.reflect.InvocationHandler; 21 import java.lang.reflect.Method; 22 import java.util.Map; 23 import junit.framework.TestCase; 24 25 /** Tests for {@link Reflection} */ 26 public class ReflectionTest extends TestCase { 27 testGetPackageName()28 public void testGetPackageName() throws Exception { 29 assertEquals("java.lang", Reflection.getPackageName(Iterable.class)); 30 assertEquals("java", Reflection.getPackageName("java.MyType")); 31 assertEquals("java.lang", Reflection.getPackageName(Iterable.class.getName())); 32 assertEquals("", Reflection.getPackageName("NoPackage")); 33 assertEquals("java.util", Reflection.getPackageName(Map.Entry.class)); 34 } 35 testNewProxy()36 public void testNewProxy() throws Exception { 37 Runnable runnable = Reflection.newProxy(Runnable.class, X_RETURNER); 38 assertEquals("x", runnable.toString()); 39 } 40 testNewProxyCantWorkOnAClass()41 public void testNewProxyCantWorkOnAClass() throws Exception { 42 try { 43 Reflection.newProxy(Object.class, X_RETURNER); 44 fail(); 45 } catch (IllegalArgumentException expected) { 46 } 47 } 48 49 private static final InvocationHandler X_RETURNER = 50 new InvocationHandler() { 51 @Override 52 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 53 return "x"; 54 } 55 }; 56 57 private static int classesInitialized = 0; 58 59 private static class A { 60 static { 61 ++classesInitialized; 62 } 63 } 64 65 private static class B { 66 static { 67 ++classesInitialized; 68 } 69 } 70 71 private static class C { 72 static { 73 ++classesInitialized; 74 } 75 } 76 testInitialize()77 public void testInitialize() { 78 assertEquals("This test can't be included twice in the same suite.", 0, classesInitialized); 79 80 Reflection.initialize(A.class); 81 assertEquals(1, classesInitialized); 82 83 Reflection.initialize( 84 A.class, // Already initialized (above) 85 B.class, C.class); 86 assertEquals(3, classesInitialized); 87 } 88 testNullPointers()89 public void testNullPointers() { 90 new NullPointerTester().testAllPublicStaticMethods(Reflection.class); 91 } 92 } 93