1+ package org .baeldung .testmethodsecurity ;
2+
3+ import static org .junit .Assert .assertEquals ;
4+
5+ import org .baeldung .testmethodsecurity .service .UserRoleService ;
6+ import org .junit .Test ;
7+ import org .junit .runner .RunWith ;
8+ import org .springframework .beans .factory .annotation .Autowired ;
9+ import org .springframework .context .annotation .ComponentScan ;
10+ import org .springframework .context .annotation .Configuration ;
11+ import org .springframework .security .access .AccessDeniedException ;
12+ import org .springframework .security .test .context .support .WithAnonymousUser ;
13+ import org .springframework .security .test .context .support .WithMockUser ;
14+ import org .springframework .test .context .ContextConfiguration ;
15+ import org .springframework .test .context .junit4 .SpringJUnit4ClassRunner ;
16+
17+ @ RunWith (SpringJUnit4ClassRunner .class )
18+ @ ContextConfiguration
19+ public class TestMethodSecurity {
20+
21+ @ Autowired
22+ UserRoleService userRoleService ;
23+
24+ @ Configuration
25+ @ ComponentScan ("org.baeldung.testmethodsecurity.*" )
26+ public static class SpringConfig {
27+
28+ }
29+
30+ @ Test
31+ @ WithMockUser (username ="john" ,roles ={"VIEWER" })
32+ public void whenRoleViewer_callGetUserName_thenOK (){
33+ String userName = userRoleService .getUserName ();
34+ assertEquals ("john" , userName );
35+ }
36+
37+ @ Test
38+ @ WithMockUser (username ="john" ,authorities ={"SYS_ADMIN" })
39+ public void whenSysAdmin_callGetUserName_thenOK (){
40+ String userName = userRoleService .getUserName ();
41+ assertEquals ("john" , userName );
42+ }
43+
44+ @ Test (expected =AccessDeniedException .class )
45+ @ WithAnonymousUser
46+ public void whenAnomynous_callGetUserName_thenFail (){
47+ userRoleService .getUserName ();
48+ }
49+
50+ @ Test
51+ @ WithMockJohnViewer
52+ public void whenJohnViewer_callGetUserName_thenOK (){
53+ String userName = userRoleService .getUserName ();
54+ assertEquals ("john" , userName );
55+ }
56+
57+ }
0 commit comments