Created
May 5, 2021 13:24
-
-
Save walidum/84e14c7c7b81b6d79cbfc9915dfc1910 to your computer and use it in GitHub Desktop.
WebTestClient
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@RunWith(SpringRunner.class) | |
@ContextConfiguration(classes = HelloWebfluxMethodApplication.class) | |
public class HelloWebfluxMethodApplicationTests { | |
@Autowired | |
ApplicationContext context; | |
WebTestClient rest; | |
@Before | |
public void setup() { | |
this.rest = WebTestClient | |
.bindToApplicationContext(this.context) | |
// add Spring Security test Support | |
.apply(springSecurity()) | |
.configureClient() | |
.filter(basicAuthentication()) | |
.build(); | |
} | |
// ... | |
@Test | |
public void messageWhenNotAuthenticated() throws Exception { | |
this.rest | |
.get() | |
.uri("/message") | |
.exchange() | |
.expectStatus().isUnauthorized(); | |
} | |
// --- WithMockUser --- | |
@Test | |
@WithMockUser | |
public void messageWhenWithMockUserThenForbidden() throws Exception { | |
this.rest | |
.get() | |
.uri("/message") | |
.exchange() | |
.expectStatus().isEqualTo(HttpStatus.FORBIDDEN); | |
} | |
@Test | |
@WithMockUser(roles = "ADMIN") | |
public void messageWhenWithMockAdminThenOk() throws Exception { | |
this.rest | |
.get() | |
.uri("/message") | |
.exchange() | |
.expectStatus().isOk() | |
.expectBody(String.class).isEqualTo("Hello World!"); | |
} | |
// --- mutateWith mockUser --- | |
@Test | |
public void messageWhenMutateWithMockUserThenForbidden() throws Exception { | |
this.rest | |
.mutateWith(mockUser()) | |
.get() | |
.uri("/message") | |
.exchange() | |
.expectStatus().isEqualTo(HttpStatus.FORBIDDEN); | |
} | |
@Test | |
public void messageWhenMutateWithMockAdminThenOk() throws Exception { | |
this.rest | |
.mutateWith(mockUser().roles("ADMIN")) | |
.get() | |
.uri("/message") | |
.exchange() | |
.expectStatus().isOk() | |
.expectBody(String.class).isEqualTo("Hello World!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment