1   package samples.annotations;
2   
3   import junit.framework.TestCase;
4   import org.acegisecurity.AccessDeniedException;
5   import org.acegisecurity.GrantedAuthority;
6   import org.acegisecurity.GrantedAuthorityImpl;
7   import org.acegisecurity.context.SecurityContextHolder;
8   import org.acegisecurity.context.SecurityContextImpl;
9   import org.acegisecurity.providers.TestingAuthenticationToken;
10  
11  import org.springframework.context.support.ClassPathXmlApplicationContext;
12  
13  import sample.annotations.BankService;
14  
15  
16  /***
17  * Tests security objects.
18  *
19  * @author Ben Alex
20  * @version $Id: BankTests.java,v 1.2 2005/11/17 00:56:47 benalex Exp $
21  */
22  public class BankTests extends TestCase {
23     //~ Instance fields ========================================================
24  
25     private BankService service;
26     private ClassPathXmlApplicationContext ctx;
27  
28     //~ Constructors ===========================================================
29  
30     public BankTests() {
31         super();
32     }
33  
34     public BankTests(String arg0) {
35         super(arg0);
36     }
37  
38     //~ Methods ================================================================
39  
40     public final void setUp() throws Exception {
41         super.setUp();
42         ctx = new ClassPathXmlApplicationContext("applicationContext-annotations.xml");
43         service = (BankService) ctx.getBean("bankService");
44     }
45  
46     public static void main(String[] args) {
47         junit.textui.TestRunner.run(BankTests.class);
48     }
49  
50     public void testDeniedAccess() throws Exception {
51         createSecureContext();
52  
53         try {
54             service.balance("1");
55             fail("Should have thrown AccessDeniedException");
56         } catch (AccessDeniedException expected) {
57             assertTrue(true);
58         }
59  
60         destroySecureContext();
61     }
62  
63     public void testListAccounts() throws Exception {
64         createSecureContext();
65         service.listAccounts();
66         destroySecureContext();
67     }
68  
69     private static void createSecureContext() {
70         TestingAuthenticationToken auth = new TestingAuthenticationToken("test",
71                 "test",
72                 new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_TELLER"), new GrantedAuthorityImpl(
73                         "ROLE_PERMISSION_LIST")});
74  
75         SecurityContextHolder.getContext().setAuthentication(auth);
76     }
77  
78     private static void destroySecureContext() {
79         SecurityContextHolder.setContext(new SecurityContextImpl());
80     }
81  }
82