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.Mockito.verify;
8   import static org.mockito.MockitoAnnotations.initMocks;
9   
10  public class TestContextClassLoaderSwitchingUtil extends TestCase {
11      @Mock
12      private ClassLoader newLoader;
13  
14      public void setUp() {
15          initMocks(this);
16      }
17  
18      public void testSwitchClassLoader() {
19          ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
20          ContextClassLoaderSwitchingUtil.runInContext(newLoader, new Runnable() {
21              public void run() {
22                  assertEquals(newLoader, Thread.currentThread().getContextClassLoader());
23                  newLoader.getResource("test");
24              }
25          });
26  
27          // Verify the loader is set back.
28          assertEquals(currentLoader, Thread.currentThread().getContextClassLoader());
29  
30          // Verify the code was actually called
31          verify(newLoader).getResource("test");
32      }
33  
34      public void testSwitchClassLoaderMultiple() {
35          ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
36          ContextClassLoaderSwitchingUtil.runInContext(newLoader, new Runnable() {
37              public void run() {
38                  assertEquals(newLoader, Thread.currentThread().getContextClassLoader());
39                  newLoader.getResource("test");
40                  final ClassLoader innerLoader = mock(ClassLoader.class);
41                  ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
42                  ContextClassLoaderSwitchingUtil.runInContext(innerLoader, new Runnable() {
43                      public void run() {
44                          assertEquals(innerLoader, Thread.currentThread().getContextClassLoader());
45                          innerLoader.getResource("test");
46                      }
47                  });
48  
49                  // Verify the loader is set back.
50                  assertEquals(currentLoader, Thread.currentThread().getContextClassLoader());
51  
52                  // Verify the code was actually called
53                  verify(newLoader).getResource("test");
54              }
55          });
56  
57          // Verify the loader is set back.
58          assertEquals(currentLoader, Thread.currentThread().getContextClassLoader());
59  
60          // Verify the code was actually called
61          verify(newLoader).getResource("test");
62      }
63  }