|
| 1 | +package org.baeldung.methodsecurity; |
| 2 | + |
| 3 | +import static org.junit.Assert.*; |
| 4 | + |
| 5 | +import org.baeldung.methodsecurity.service.SystemService; |
| 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.WithMockUser; |
| 13 | +import org.springframework.test.context.ContextConfiguration; |
| 14 | +import org.springframework.test.context.junit4.SpringRunner; |
| 15 | + |
| 16 | +@RunWith(SpringRunner.class) |
| 17 | +@ContextConfiguration |
| 18 | +public class TestClassLevelSecurity { |
| 19 | + |
| 20 | + @Autowired |
| 21 | + SystemService systemService; |
| 22 | + |
| 23 | + @Configuration |
| 24 | + @ComponentScan("org.baeldung.methodsecurity.*") |
| 25 | + public static class SpringConfig { |
| 26 | + |
| 27 | + } |
| 28 | + |
| 29 | + @Test |
| 30 | + @WithMockUser(username="john",roles={"ADMIN"}) |
| 31 | + public void givenRoleAdmin_whenCallGetSystemYear_return2017(){ |
| 32 | + String systemYear = systemService.getSystemYear(); |
| 33 | + assertEquals("2017",systemYear); |
| 34 | + } |
| 35 | + |
| 36 | + @Test(expected=AccessDeniedException.class) |
| 37 | + @WithMockUser(username="john",roles={"VIEWER"}) |
| 38 | + public void givenRoleViewer_whenCallGetSystemYear_returnAccessDenied(){ |
| 39 | + String systemYear = systemService.getSystemYear(); |
| 40 | + assertEquals("2017",systemYear); |
| 41 | + } |
| 42 | + |
| 43 | + @Test |
| 44 | + @WithMockUser(username="john",roles={"ADMIN"}) |
| 45 | + public void givenRoleAdmin_whenCallGetSystemDate_returnDate(){ |
| 46 | + String systemYear = systemService.getSystemDate(); |
| 47 | + assertEquals("31-12-2017",systemYear); |
| 48 | + } |
| 49 | +} |
0 commit comments