|
| 1 | +package org.baeldung.web; |
| 2 | + |
| 3 | +import static org.assertj.core.api.Assertions.assertThat; |
| 4 | + |
| 5 | +import java.util.Collections; |
| 6 | + |
| 7 | +import org.baeldung.multipleauthproviders.MultipleAuthProvidersApplication; |
| 8 | +import org.junit.Test; |
| 9 | +import org.junit.runner.RunWith; |
| 10 | +import org.springframework.beans.factory.annotation.Autowired; |
| 11 | +import org.springframework.boot.test.context.SpringBootTest; |
| 12 | +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; |
| 13 | +import org.springframework.boot.test.web.client.TestRestTemplate; |
| 14 | +import org.springframework.http.ResponseEntity; |
| 15 | +import org.springframework.test.context.junit4.SpringRunner; |
| 16 | + |
| 17 | +@RunWith(SpringRunner.class) |
| 18 | +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = MultipleAuthProvidersApplication.class) |
| 19 | +public class MultipleAuthProvidersApplicationTests { |
| 20 | + @Autowired |
| 21 | + private TestRestTemplate restTemplate; |
| 22 | + |
| 23 | + @Test |
| 24 | + public void givenMemUsers_whenGetPingWithValidUser_thenOk() { |
| 25 | + ResponseEntity<String> result = makeRestCallToGetPing("memuser", "pass"); |
| 26 | + |
| 27 | + assertThat(result.getStatusCodeValue()).isEqualTo(200); |
| 28 | + assertThat(result.getBody()).isEqualTo("OK"); |
| 29 | + } |
| 30 | + |
| 31 | + @Test |
| 32 | + public void givenExternalUsers_whenGetPingWithValidUser_thenOK() { |
| 33 | + ResponseEntity<String> result = makeRestCallToGetPing("externaluser", "pass"); |
| 34 | + |
| 35 | + assertThat(result.getStatusCodeValue()).isEqualTo(200); |
| 36 | + assertThat(result.getBody()).isEqualTo("OK"); |
| 37 | + } |
| 38 | + |
| 39 | + @Test |
| 40 | + public void givenAuthProviders_whenGetPingWithNoCred_then401() { |
| 41 | + ResponseEntity<String> result = makeRestCallToGetPing(); |
| 42 | + |
| 43 | + assertThat(result.getStatusCodeValue()).isEqualTo(401); |
| 44 | + } |
| 45 | + |
| 46 | + @Test |
| 47 | + public void givenAuthProviders_whenGetPingWithBadCred_then401() { |
| 48 | + ResponseEntity<String> result = makeRestCallToGetPing("user", "bad_password"); |
| 49 | + |
| 50 | + assertThat(result.getStatusCodeValue()).isEqualTo(401); |
| 51 | + } |
| 52 | + |
| 53 | + private ResponseEntity<String> makeRestCallToGetPing(String username, String password) { |
| 54 | + return restTemplate.withBasicAuth(username, password) |
| 55 | + .getForEntity("/api/ping", String.class, Collections.emptyMap()); |
| 56 | + } |
| 57 | + |
| 58 | + private ResponseEntity<String> makeRestCallToGetPing() { |
| 59 | + return restTemplate.getForEntity("/api/ping", String.class, Collections.emptyMap()); |
| 60 | + } |
| 61 | +} |
0 commit comments