Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @RestController
- @RequiredArgsConstructor
- @RequestMapping("/api/certificates")
- public class CertificateController {
- private final CertificateService certificateService;
- // ...
- /**
- * GET endpoint to search for certificates based on search parameters
- *
- * @param page page number requested (default is 0)
- * @param size number of items per page (default is 5)
- * @param searchFilter holding search parameters
- * @return page of certificates based on provided search parameters
- */
- @PostMapping("/search")
- @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
- public Page<CertificateDto> search(@RequestParam(defaultValue = "0") int page,
- @RequestParam(defaultValue = "5") int size,
- @RequestBody(required = false) SearchFilter searchFilter) {
- return certificateService.findByFilterAndPage(searchFilter, page, size);
- }
- // ...
- }
- @WebMvcTest(CertificateController.class)
- @ContextConfiguration(classes = AuthenticationManager.class)
- class CertificateControllerTest {
- @Autowired
- private MockMvc mockMvc;
- @MockBean
- private CertificateService certificateService;
- // ...
- @Test
- @WithMockUser(roles = "GUEST")
- void searchShouldBeForbiddenForGuest() throws Exception {
- this.mockMvc.perform(post("/api/certificates/search")).andDo(print())
- .andExpect(isForbidden(true));
- }
- @Test
- @WithMockUser(roles = "USER")
- void searchShouldNotBeForbiddenForUser() throws Exception {
- this.mockMvc.perform(post("/api/certificates/search")).andDo(print())
- .andExpect(isForbidden(false));
- }
- @Test
- @WithMockUser(roles = "ADMIN")
- void searchShouldNotBeForbiddenForAdmin() throws Exception {
- this.mockMvc.perform(post("/api/certificates/search")).andDo(print())
- .andExpect(isForbidden(false));
- }
- private ResultMatcher isForbidden(boolean forbidden) {
- if (forbidden) {
- return result -> assertEquals("Status",
- HttpStatus.FORBIDDEN.value(), result.getResponse().getStatus());
- }
- return result -> assertNotEquals("Status",
- HttpStatus.FORBIDDEN.value(), result.getResponse().getStatus());
- }
- // ...
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement