|
| 1 | +package com.baeldung.inmemory; |
| 2 | + |
| 3 | +import static org.junit.Assert.assertEquals; |
| 4 | + |
| 5 | +import org.junit.Test; |
| 6 | +import org.junit.runner.RunWith; |
| 7 | +import org.springframework.beans.factory.annotation.Autowired; |
| 8 | +import org.springframework.boot.test.context.SpringBootTest; |
| 9 | +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; |
| 10 | +import org.springframework.boot.test.web.client.TestRestTemplate; |
| 11 | +import org.springframework.http.HttpStatus; |
| 12 | +import org.springframework.http.ResponseEntity; |
| 13 | +import org.springframework.test.context.junit4.SpringRunner; |
| 14 | + |
| 15 | +@RunWith(SpringRunner.class) |
| 16 | +@SpringBootTest(classes = InMemoryAuthApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) |
| 17 | +public class InMemoryAuthControllerTest { |
| 18 | + |
| 19 | + @Autowired |
| 20 | + private TestRestTemplate template; |
| 21 | + |
| 22 | + @Test |
| 23 | + public void givenRequestOnPublicService_shouldSucceedWith200() throws Exception { |
| 24 | + ResponseEntity<String> result = template.getForEntity("/public/hello", String.class); |
| 25 | + assertEquals(HttpStatus.OK, result.getStatusCode()); |
| 26 | + } |
| 27 | + |
| 28 | + @Test |
| 29 | + public void givenRequestOnPrivateService_shouldFailWith401() throws Exception { |
| 30 | + ResponseEntity<String> result = template.getForEntity("/private/hello", String.class); |
| 31 | + assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); |
| 32 | + } |
| 33 | + |
| 34 | + @Test |
| 35 | + public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { |
| 36 | + ResponseEntity<String> result = template.withBasicAuth("spring", "secret") |
| 37 | + .getForEntity("/private/hello", String.class); |
| 38 | + assertEquals(HttpStatus.OK, result.getStatusCode()); |
| 39 | + } |
| 40 | + |
| 41 | + @Test |
| 42 | + public void givenInvalidAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { |
| 43 | + ResponseEntity<String> result = template.withBasicAuth("spring", "wrong") |
| 44 | + .getForEntity("/private/hello", String.class); |
| 45 | + assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); |
| 46 | + } |
| 47 | + |
| 48 | +} |
0 commit comments