When I try to implement a WebMvcTest it attempts to instantiate every application controller rather than just the one indicated on the @WebMvcTest
annotation.
Without any luck or success, I've read these articles:
- Spring Boot Testing @WebMvcTest for a Controller appears to load other controllers in the context
- @WebMvcTest fails with java.lang.IllegalStateException: Failed to load ApplicationContext
- @WebMvcTest creating more than one Controller for some reason
- Test slice with @WebMvcTest is loading a substantial amount of controllers unrelated with the target
And here are the parts of my code that I found relevant
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RestController
@RequestMapping("/api/complaints/{id}/comments")
public class CommentController {
@PostMapping
public CommentJson comment(@PathVariable String id, @RequestBody CommentCommand command) {
throw new UnsupportedOperationException("Method not implemented yet");
}
}
@WebMvcTest(CommentController.class)
class CommentControllerTest extends AbstractTest {
@Autowired
MockMvc mockMvc;
// ...
}
When I run the tests it fails with the following error:
Parameter 0 of constructor in com.company.package.controller.ComplaintController required a bean of type 'com.company.package.service.Complaints' that could not be found.
@RestController
@RequestMapping("/api/complaints")
@RequiredArgsConstructor
@ControllerAdvice()
public class ComplaintController {
private final Complaints complaints;
// ... other controller methods
@ExceptionHandler(ComplaintNotFoundException.class)
public ResponseEntity<Void> handleComplaintNotFoundException() {
return ResponseEntity.notFound().build();
}
}
@ExtendWith(MockitoExtension.class)
public abstract class AbstractTest {
private final Faker faker = new Faker();
protected final Faker faker() {
return faker;
}
// ... other utility methods
}
The only way I found to make my Web Mvc Tests run is to mock every dependency of each controller on all @WebMvcTest
which is very tedious.
Am I missing something here?