Improve anonymous tests readability

This commit is contained in:
ch4mpy
2023-02-17 12:18:02 -10:00
parent 03c3de438c
commit 3a6f99223a
6 changed files with 34 additions and 15 deletions

View File

@@ -36,7 +36,9 @@ class ServletResourceServerApplicationIntegrationTest {
}
@Test
@WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy"))
@WithMockJwtAuth(
authorities = {"admin", "ROLE_AUTHORIZED_PERSONNEL"},
claims = @OpenIdClaims(preferredUsername = "ch4mpy"))
void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception {
// @formatter:off
api.perform(get("/greet"))

View File

@@ -16,6 +16,7 @@ import org.springframework.test.web.servlet.MockMvc;
import com.baeldung.ServletResourceServerApplication.GreetingController;
import com.baeldung.ServletResourceServerApplication.MessageService;
import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth;
@WebMvcTest(controllers = GreetingController.class, properties = { "server.ssl.enabled=false" })
@@ -42,7 +43,9 @@ class SpringAddonsGreetingControllerUnitTest {
}
@Test
@WithMockJwtAuth
@WithMockJwtAuth(
authorities = {"admin", "ROLE_AUTHORIZED_PERSONNEL"},
claims = @OpenIdClaims(preferredUsername = "ch4mpy"))
void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception {
final var greeting = "Whatever the service returns";
when(messageService.greet()).thenReturn(greeting);

View File

@@ -9,11 +9,14 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
import org.springframework.test.web.servlet.MockMvc;
import com.baeldung.ServletResourceServerApplication.GreetingController;
@@ -47,7 +50,9 @@ class SpringSecurityTestGreetingControllerUnitTest {
when(messageService.greet()).thenReturn(greeting);
// @formatter:off
api.perform(get("/greet").with(jwt()))
api.perform(get("/greet").with(jwt()
.authorities(List.of(new SimpleGrantedAuthority("admin"), new SimpleGrantedAuthority("ROLE_AUTHORIZED_PERSONNEL")))
.jwt(jwt -> jwt.claim(StandardClaimNames.PREFERRED_USERNAME, "ch4mpy"))))
.andExpect(status().isOk())
.andExpect(content().string(greeting));
// @formatter:on