View Javadoc

1   package com.atlassian.plugin.util;
2   
3   import junit.framework.TestCase;
4   import org.mockito.Mock;
5   
6   import static org.mockito.Mockito.mock;
7   import static org.mockito.MockitoAnnotations.initMocks;
8   import static org.mockito.Mockito.verify;
9   
10  public class TestContextClassLoaderSwitchingUtil extends TestCase
11  {
12      @Mock private ClassLoader newLoader;
13  
14      public void setUp()
15      {
16          initMocks(this);
17      }
18  
19      public void testSwitchClassLoader()
20      {
21          ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
22          ContextClassLoaderSwitchingUtil.runInContext(newLoader, new Runnable()
23          {
24              public void run()
25              {
26                  assertEquals(newLoader, Thread.currentThread().getContextClassLoader());
27                  newLoader.getResource("test");
28              }
29          });
30  
31          // Verify the loader is set back.
32          assertEquals(currentLoader, Thread.currentThread().getContextClassLoader());
33  
34          // Verify the code was actually called
35          verify(newLoader).getResource("test");
36      }
37  
38      public void testSwitchClassLoaderMultiple()
39      {
40          ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
41          ContextClassLoaderSwitchingUtil.runInContext(newLoader, new Runnable()
42          {
43              public void run()
44              {
45                  assertEquals(newLoader, Thread.currentThread().getContextClassLoader());
46                      newLoader.getResource("test");
47                  final ClassLoader innerLoader = mock(ClassLoader.class);
48                  ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
49                  ContextClassLoaderSwitchingUtil.runInContext(innerLoader, new Runnable()
50                  {
51                      public void run()
52                      {
53                          assertEquals(innerLoader, Thread.currentThread().getContextClassLoader());
54                          innerLoader.getResource("test");
55                      }
56                  });
57  
58                  // Verify the loader is set back.
59                  assertEquals(currentLoader, Thread.currentThread().getContextClassLoader());
60  
61                  // Verify the code was actually called
62                  verify(newLoader).getResource("test");
63              }
64          });
65  
66          // Verify the loader is set back.
67          assertEquals(currentLoader, Thread.currentThread().getContextClassLoader());
68  
69          // Verify the code was actually called
70          verify(newLoader).getResource("test");
71      }
72  }