|
| 1 | +package com.baeldung.springsecuritytaglibs; |
| 2 | + |
| 3 | +import static org.junit.Assert.assertFalse; |
| 4 | +import static org.junit.Assert.assertTrue; |
| 5 | + |
| 6 | +import org.junit.Test; |
| 7 | +import org.junit.runner.RunWith; |
| 8 | +import org.springframework.beans.factory.annotation.Autowired; |
| 9 | +import org.springframework.boot.test.context.SpringBootTest; |
| 10 | +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; |
| 11 | +import org.springframework.boot.test.web.client.TestRestTemplate; |
| 12 | +import org.springframework.test.context.junit4.SpringRunner; |
| 13 | + |
| 14 | +@RunWith(SpringRunner.class) |
| 15 | +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SpringBootSecurityTagLibsApplication.class) |
| 16 | +public class HomeControllerUnitTest { |
| 17 | + |
| 18 | + @Autowired |
| 19 | + private TestRestTemplate restTemplate; |
| 20 | + |
| 21 | + @Test |
| 22 | + public void whenUserIsAuthenticatedThenAuthenticatedSectionsShowOnSite() throws Exception { |
| 23 | + String body = this.restTemplate.withBasicAuth("testUser", "password") |
| 24 | + .getForEntity("/", String.class) |
| 25 | + .getBody(); |
| 26 | + |
| 27 | + // test <sec:authorize access="!isAuthenticated()"> |
| 28 | + assertFalse(body.contains("Login")); |
| 29 | + |
| 30 | + // test <sec:authorize access="isAuthenticated()"> |
| 31 | + assertTrue(body.contains("Logout")); |
| 32 | + |
| 33 | + // test <sec:authorize access="hasRole('ADMIN')"> |
| 34 | + assertTrue(body.contains("Manage Users")); |
| 35 | + |
| 36 | + // test <sec:authentication property="principal.username" /> |
| 37 | + assertTrue(body.contains("testUser")); |
| 38 | + |
| 39 | + // test <sec:authorize url="/adminOnlyURL"> |
| 40 | + assertTrue(body.contains("<a href=\"/userManagement\">")); |
| 41 | + |
| 42 | + // test <sec:csrfInput /> |
| 43 | + assertTrue(body.contains("<input type=\"hidden\" name=\"_csrf\" value=\"")); |
| 44 | + |
| 45 | + // test <sec:csrfMetaTags /> |
| 46 | + assertTrue(body.contains("<meta name=\"_csrf_parameter\" content=\"_csrf\" />")); |
| 47 | + } |
| 48 | + |
| 49 | + @Test |
| 50 | + public void whenUserIsNotAuthenticatedThenOnlyAnonymousSectionsShowOnSite() throws Exception { |
| 51 | + String body = this.restTemplate.getForEntity("/", String.class) |
| 52 | + .getBody(); |
| 53 | + |
| 54 | + // test <sec:authorize access="!isAuthenticated()"> |
| 55 | + assertTrue(body.contains("Login")); |
| 56 | + |
| 57 | + // test <sec:authorize access="isAuthenticated()"> |
| 58 | + assertFalse(body.contains("Logout")); |
| 59 | + } |
| 60 | +} |
0 commit comments