1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.shiro.test;
20
21 import org.apache.shiro.SecurityUtils;
22 import org.apache.shiro.UnavailableSecurityManagerException;
23 import org.apache.shiro.mgt.SecurityManager;
24 import org.apache.shiro.subject.Subject;
25 import org.apache.shiro.subject.support.SubjectThreadState;
26 import org.apache.shiro.util.LifecycleUtils;
27 import org.apache.shiro.util.ThreadState;
28 import org.junit.AfterClass;
29
30
31
32
33
34
35 public abstract class AbstractShiroTest {
36
37 private static ThreadState subjectThreadState;
38
39 public AbstractShiroTest() {
40 }
41
42
43
44
45
46
47 protected void setSubject(Subject subject) {
48 clearSubject();
49 subjectThreadState = createThreadState(subject);
50 subjectThreadState.bind();
51 }
52
53 protected Subject getSubject() {
54 return SecurityUtils.getSubject();
55 }
56
57 protected ThreadState createThreadState(Subject subject) {
58 return new SubjectThreadState(subject);
59 }
60
61
62
63
64 protected void clearSubject() {
65 doClearSubject();
66 }
67
68 private static void doClearSubject() {
69 if (subjectThreadState != null) {
70 subjectThreadState.clear();
71 subjectThreadState = null;
72 }
73 }
74
75 protected static void setSecurityManager(SecurityManager securityManager) {
76 SecurityUtils.setSecurityManager(securityManager);
77 }
78
79 protected static SecurityManager getSecurityManager() {
80 return SecurityUtils.getSecurityManager();
81 }
82
83 @AfterClass
84 public static void tearDownShiro() {
85 doClearSubject();
86 try {
87 SecurityManager securityManager = getSecurityManager();
88 LifecycleUtils.destroy(securityManager);
89 } catch (UnavailableSecurityManagerException e) {
90
91
92
93 }
94 setSecurityManager(null);
95 }
96 }