@WebMvcTest(TaskController.class)
class TaskControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private TaskService taskService;
@Test
public void shouldRejectCreatingReviewsWhenUserIsAnonymous() throws Exception {
this.mockMvc
.perform(
post("/api/tasks")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"taskTitle\": \"Learn MockMvc\"}")
.with(csrf())
)
.andExpect(status().isUnauthorized());
}
}
@Test
public void shouldReturnLocationOfReviewWhenUserIsAuthenticatedAndCreatesReview() throws Exception {
when(taskService.createTask(anyString())).thenReturn(42L);
this.mockMvc
.perform(
post("/api/tasks")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"taskTitle\": \"Learn MockMvc\"}")
.with(csrf())
.with(SecurityMockMvcRequestPostProcessors.user("duke"))
)
.andExpect(status().isCreated())
.andExpect(header().exists("Location"))
.andExpect(header().string("Location", Matchers.containsString("42")));
}
@Test
public void shouldAllowDeletingReviewsWhenUserIsAdmin() throws Exception {
this.mockMvc
.perform(
delete("/api/tasks/42")
.with(user("duke").roles("ADMIN", "SUPER_USER"))
.with(csrf())
)
.andExpect(status().isOk());
verify(taskService).deleteTask(42L);
}
@Test
@WithMockUser("duke")
public void shouldRejectDeletingReviewsWhenUserLacksAdminRole() throws Exception {
this.mockMvc
.perform(delete("/api/tasks/42"))
.andExpect(status().isForbidden());
}