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 private ClassLoader mainLoader;
15
16 @Before
17 public void setUp() throws Exception {
18 mainLoader = Thread.currentThread().getContextClassLoader();
19 }
20
21 @After
22 public void tearDown() throws Exception {
23 Thread.currentThread().setContextClassLoader(mainLoader);
24 }
25
26 @Test
27 public void testThreadClassLoaderIsReplacedAndRestored() throws URISyntaxException {
28 ClassLoader pluginLoader1 = new MockClassLoader();
29 ClassLoader pluginLoader2 = new MockClassLoader();
30
31 ClassLoaderStack.push(pluginLoader1);
32 assertSame(pluginLoader1, Thread.currentThread().getContextClassLoader());
33 ClassLoaderStack.push(pluginLoader2);
34 assertSame(pluginLoader2, Thread.currentThread().getContextClassLoader());
35 ClassLoaderStack.pop();
36 assertSame(pluginLoader1, Thread.currentThread().getContextClassLoader());
37 ClassLoaderStack.pop();
38 assertSame(mainLoader, Thread.currentThread().getContextClassLoader());
39 }
40
41 @Test
42 public void testPopReturnsPreviousContextClassLoader() throws Exception {
43 ClassLoader pluginLoader1 = new MockClassLoader();
44 ClassLoader pluginLoader2 = new MockClassLoader();
45
46 ClassLoaderStack.push(pluginLoader1);
47 assertSame(pluginLoader1, Thread.currentThread().getContextClassLoader());
48 ClassLoaderStack.push(pluginLoader2);
49 assertSame(pluginLoader2, Thread.currentThread().getContextClassLoader());
50 ClassLoader previous = ClassLoaderStack.pop();
51 assertSame(pluginLoader2, previous);
52 assertSame(pluginLoader1, Thread.currentThread().getContextClassLoader());
53 previous = ClassLoaderStack.pop();
54 assertSame(pluginLoader1, previous);
55 assertSame(mainLoader, Thread.currentThread().getContextClassLoader());
56 }
57
58 @Test
59 public void testPushAndPopHandleNull() throws Exception {
60
61 assertNull(ClassLoaderStack.pop());
62
63 ClassLoaderStack.push(null);
64 assertSame(mainLoader, Thread.currentThread().getContextClassLoader());
65 assertNull(ClassLoaderStack.pop());
66 }
67
68 public static class MockClassLoader extends ClassLoader {
69 }
70 }