【发布时间】:2021-02-19 18:52:20
【问题描述】:
当我尝试实现 WebMvcTest 时,它会尝试实例化每个应用程序控制器,而不仅仅是 @WebMvcTest 注释中指示的那个。
没有任何运气或成功,我读过这些文章:
- 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
这是我发现相关的代码部分
@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;
// ...
}
当我运行测试失败并出现以下错误:
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
}
我发现让我的 Web Mvc 测试运行的唯一方法是模拟每个控制器对所有 @WebMvcTest 的每个依赖项,这非常乏味。
我在这里遗漏了什么吗?
【问题讨论】:
-
请为你的
AbstractTest类添加代码 -
@rieckpil 我已经更新并包含了
AbstractTest类
标签: java spring spring-test-mvc