1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.grouplens.grapht.util;
21
22 import org.junit.Test;
23
24 import java.net.URL;
25 import java.net.URLClassLoader;
26
27 import static org.hamcrest.Matchers.equalTo;
28 import static org.hamcrest.Matchers.notNullValue;
29 import static org.hamcrest.Matchers.sameInstance;
30 import static org.junit.Assert.assertThat;
31 import static org.junit.Assert.fail;
32 import static org.junit.Assume.assumeThat;
33
34
35
36
37
38 public class ClassLoadersTest {
39 @Test
40 public void testPushContextClassLoader() throws Exception {
41 Thread th = Thread.currentThread();
42 ClassLoader orig = th.getContextClassLoader();
43 ClassLoader loader = new URLClassLoader(new URL[0], ClassLoaders.inferDefault(ClassLoadersTest.class));
44 ClassLoaderContext ctx = ClassLoaders.pushContext(loader);
45 try {
46 assertThat(th.getContextClassLoader(), sameInstance(loader));
47 } finally {
48 ctx.pop();
49 }
50 assertThat(th.getContextClassLoader(), sameInstance(orig));
51 try {
52 ctx.pop();
53 fail("re-popping context should be illegal state");
54 } catch (IllegalStateException e) {
55
56 }
57 }
58
59 @Test
60 public void testInferLoaderFromRefClass() throws Exception {
61 Thread th = Thread.currentThread();
62 ClassLoader orig = th.getContextClassLoader();
63 assumeThat("have a context class loader",
64 orig, notNullValue());
65 ClassLoaderContext ctx = ClassLoaders.pushContext(null);
66 try {
67 assertThat(ClassLoaders.inferDefault(ClassLoadersTest.class),
68 equalTo(getClass().getClassLoader()));
69 } finally {
70 ctx.pop();
71 }
72 }
73
74 @Test
75 public void testInferLoaderFromThread() throws Exception {
76 Thread th = Thread.currentThread();
77 ClassLoader orig = th.getContextClassLoader();
78 assumeThat("have a context class loader",
79 orig, notNullValue());
80 assertThat(ClassLoaders.inferDefault(ClassLoadersTest.class),
81 equalTo(orig));
82 }
83 }