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