1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19 package org.apache.shiro.test;
20
21 import org.apache.shiro.config.IniSecurityManagerFactory;
22 import org.apache.shiro.mgt.SecurityManager;
23 import org.apache.shiro.subject.Subject;
24 import org.apache.shiro.util.Factory;
25 import org.junit.After;
26 import org.junit.BeforeClass;
27 import org.junit.Test;
28
29 /**
30 * Simple example test class to be used to show how one might write Shiro-compatible unit tests.
31 *
32 * @since 1.2
33 */
34 public class ExampleShiroIntegrationTest extends AbstractShiroTest {
35
36 @BeforeClass
37 public static void beforeClass() {
38 //0. Build and set the SecurityManager used to build Subject instances used in your tests
39 // This typically only needs to be done once per class if your shiro.ini doesn't change,
40 // otherwise, you'll need to do this logic in each test that is different
41 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:test.shiro.ini");
42 setSecurityManager(factory.getInstance());
43 }
44
45 @Test
46 public void testSimple() {
47 //1. Build the Subject instance for the test to run:
48 Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();
49
50 //2. Bind the subject to the current thread:
51 setSubject(subjectUnderTest);
52
53 //perform test logic here. Any call to
54 //SecurityUtils.getSubject() directly (or nested in the
55 //call stack) will work properly.
56 }
57
58 @After
59 public void tearDownSubject() {
60 //3. Unbind the subject from the current thread:
61 clearSubject();
62 }
63 }