View Javadoc
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   
9   @SuppressWarnings("AssertEqualsBetweenInconvertibleTypes")
10  public class TestClassLoaderUtils {
11      @Test
12      public void testLoadClassWithContextClassLoader() throws Exception {
13          withContextClassLoaderTest(Thread.currentThread().getContextClassLoader(), new Callable<Void>() {
14              @Override
15              public Void call() throws Exception {
16                  assertEquals(TestClassLoaderUtils.class, ClassLoaderUtils.loadClass(TestClassLoaderUtils.class.getName(), this.getClass()));
17                  return null;
18              }
19          });
20      }
21  
22      @Test(expected = ClassNotFoundException.class)
23      public void testLoadNoSuchClassWithContextClassLoader() throws Exception {
24          withContextClassLoaderTest(Thread.currentThread().getContextClassLoader(), new Callable<Void>() {
25              @Override
26              public Void call() throws Exception {
27                  ClassLoaderUtils.loadClass("some.class", null);
28                  return null;
29              }
30          });
31      }
32  
33      @Test
34      public void testLoadClassWithNullContextClassLoader() throws Exception {
35          withContextClassLoaderTest(null, new Callable<Void>() {
36              @Override
37              public Void call() throws Exception {
38                  assertEquals(TestClassLoaderUtils.class, ClassLoaderUtils.loadClass(TestClassLoaderUtils.class.getName(), this.getClass()));
39                  return null;
40              }
41          });
42      }
43  
44      @Test(expected = ClassNotFoundException.class)
45      public void testLoadNoSuchClassWithNullContextClassLoader() throws Exception {
46          withContextClassLoaderTest(null, new Callable<Void>() {
47              @Override
48              public Void call() throws Exception {
49                  ClassLoaderUtils.loadClass("some.class", null);
50                  return null;
51              }
52          });
53      }
54  
55      private void withContextClassLoaderTest(ClassLoader contextClassLoader, Callable<Void> test) throws Exception {
56          ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
57          Thread.currentThread().setContextClassLoader(contextClassLoader);
58          try {
59              test.call();
60          } finally {
61              Thread.currentThread().setContextClassLoader(currentClassLoader);
62          }
63      }
64  }