Cannot initialize MockMvc in Spock test class

30 Views Asked by At
@RestController
@RequestMapping("/api/task")
@RequiredArgsConstructor
@Validated
@Slf4j
public class TaskController {

    private final TaskService taskService;
    private final TaskMapper taskMapper;

    // Mapping methods 
}
@SpringBootTest
class TaskControllerSpec extends Specification {

    @MockBean
    def taskService
    @Shared
    def taskController = new TaskController(taskService, {})
    @Shared
    MockMvc mockMvc
    @Shared
    private int id
    @Shared
    private UpdateTaskRequest updateTaskRequest
    @Shared
    private CreateTaskRequest createTaskRequest

    void setupSpec() {
        mockMvc = standaloneSetup(taskController)
        updateTaskRequest = new UpdateTaskRequest("UpdatedTask", LocalDate.now().plusDays(7), null, TaskState.IN_PROGRESS)
        createTaskRequest = new CreateTaskRequest("TestTask", null, null, TaskState.TODO)

        def taskResponse = mockMvc.perform(post("/api/task")
                .contentType(MediaType.APPLICATION_JSON)
                .content(asJsonString(createTaskRequest)))
                .andExpect(status().isCreated())
                .andReturn()

        id = taskResponse.response.contentAsString.toInteger()
    }
    // Tests
}

First I tried annotation @WemMvcTest(TaskController.class) and @Autowired on MockMvc mockMvc, but it didn't work, mockMvc was always null.

Then I standaloneSetup(), as in code I provided here, but got error:

groovy.lang.MissingMethodException: No signature of method: com.example.taskmanager.web.TaskControllerSpec.standaloneSetup() is applicable for argument types: (com.example.taskmanager.web.TaskController) values: [com.example.taskmanager.web.TaskController@790132f7]
0

There are 0 best solutions below