1 package com.atlassian.plugin.util;
2
3 import org.junit.After;
4 import org.junit.Before;
5 import org.junit.Test;
6
7 import java.net.URISyntaxException;
8
9 import static org.junit.Assert.assertNull;
10 import static org.junit.Assert.assertSame;
11
12 public class TestClassLoaderStack
13 {
14
15 private ClassLoader mainLoader;
16
17 @Before
18 public void setUp() throws Exception
19 {
20 mainLoader = Thread.currentThread().getContextClassLoader();
21 }
22
23 @After
24 public void tearDown() throws Exception
25 {
26 Thread.currentThread().setContextClassLoader(mainLoader);
27 }
28
29 @Test
30 public void testThreadClassLoaderIsReplacedAndRestored() throws URISyntaxException
31 {
32 ClassLoader pluginLoader1 = new MockClassLoader();
33 ClassLoader pluginLoader2 = new MockClassLoader();
34
35 ClassLoaderStack.push(pluginLoader1);
36 assertSame(pluginLoader1, Thread.currentThread().getContextClassLoader());
37 ClassLoaderStack.push(pluginLoader2);
38 assertSame(pluginLoader2, Thread.currentThread().getContextClassLoader());
39 ClassLoaderStack.pop();
40 assertSame(pluginLoader1, Thread.currentThread().getContextClassLoader());
41 ClassLoaderStack.pop();
42 assertSame(mainLoader, Thread.currentThread().getContextClassLoader());
43 }
44
45 @Test
46 public void testPopReturnsPreviousContextClassLoader() throws Exception
47 {
48 ClassLoader pluginLoader1 = new MockClassLoader();
49 ClassLoader pluginLoader2 = new MockClassLoader();
50
51 ClassLoaderStack.push(pluginLoader1);
52 assertSame(pluginLoader1, Thread.currentThread().getContextClassLoader());
53 ClassLoaderStack.push(pluginLoader2);
54 assertSame(pluginLoader2, Thread.currentThread().getContextClassLoader());
55 ClassLoader previous = ClassLoaderStack.pop();
56 assertSame(pluginLoader2, previous);
57 assertSame(pluginLoader1, Thread.currentThread().getContextClassLoader());
58 previous = ClassLoaderStack.pop();
59 assertSame(pluginLoader1, previous);
60 assertSame(mainLoader, Thread.currentThread().getContextClassLoader());
61 }
62
63 @Test
64 public void testPushAndPopHandleNull() throws Exception
65 {
66
67 assertNull(ClassLoaderStack.pop());
68
69 ClassLoaderStack.push(null);
70 assertSame(mainLoader, Thread.currentThread().getContextClassLoader());
71 assertNull(ClassLoaderStack.pop());
72 }
73
74 public static class MockClassLoader extends ClassLoader
75 {
76 }
77 }