1 package com.atlassian.plugin.util; 2 3 import org.junit.Test; 4 5 import java.util.concurrent.Callable; 6 7 import static org.junit.Assert.assertEquals; 8 import static org.junit.Assert.assertNotNull; 9 10 @SuppressWarnings("AssertEqualsBetweenInconvertibleTypes") 11 public class TestClassLoaderUtils { 12 @Test 13 public void testLoadClassWithContextClassLoader() throws Exception { 14 withContextClassLoaderTest(Thread.currentThread().getContextClassLoader(), new Callable<Void>() { 15 @Override 16 public Void call() throws Exception { 17 assertEquals(TestClassLoaderUtils.class, ClassLoaderUtils.loadClass(TestClassLoaderUtils.class.getName(), this.getClass())); 18 return null; 19 } 20 }); 21 } 22 23 @Test(expected = ClassNotFoundException.class) 24 public void testLoadNoSuchClassWithContextClassLoader() throws Exception { 25 withContextClassLoaderTest(Thread.currentThread().getContextClassLoader(), new Callable<Void>() { 26 @Override 27 public Void call() throws Exception { 28 ClassLoaderUtils.loadClass("some.class", null); 29 return null; 30 } 31 }); 32 } 33 34 @Test 35 public void testLoadClassWithNullContextClassLoader() throws Exception { 36 withContextClassLoaderTest(null, new Callable<Void>() { 37 @Override 38 public Void call() throws Exception { 39 assertEquals(TestClassLoaderUtils.class, ClassLoaderUtils.loadClass(TestClassLoaderUtils.class.getName(), this.getClass())); 40 return null; 41 } 42 }); 43 } 44 45 @Test(expected = ClassNotFoundException.class) 46 public void testLoadNoSuchClassWithNullContextClassLoader() throws Exception { 47 withContextClassLoaderTest(null, new Callable<Void>() { 48 @Override 49 public Void call() throws Exception { 50 ClassLoaderUtils.loadClass("some.class", null); 51 return null; 52 } 53 }); 54 } 55 56 @Test 57 public void testGetResourcesWithNullContextClassLoader() throws Exception { 58 withContextClassLoaderTest(null, new Callable<Void>() { 59 @Override 60 public Void call() throws Exception { 61 assertNotNull(ClassLoaderUtils.getResources("log4j.properties", null)); 62 return null; 63 } 64 }); 65 } 66 67 @Test 68 public void testGetResourceWithNullContextClassLoader() throws Exception { 69 withContextClassLoaderTest(null, new Callable<Void>() { 70 @Override 71 public Void call() { 72 assertNotNull(ClassLoaderUtils.getResource("log4j.properties", null)); 73 return null; 74 } 75 }); 76 } 77 78 private void withContextClassLoaderTest(ClassLoader contextClassLoader, Callable<Void> test) throws Exception { 79 ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); 80 Thread.currentThread().setContextClassLoader(contextClassLoader); 81 try { 82 test.call(); 83 } finally { 84 Thread.currentThread().setContextClassLoader(currentClassLoader); 85 } 86 } 87 }