java - WebMvcTest 尝试加载每个应用程序控制器
问题描述
当我尝试实现 WebMvcTest 时,它会尝试实例化每个应用程序控制器,而不仅仅是@WebMvcTest
注释上指示的那个。
没有任何运气或成功,我读过这些文章:
- Spring Boot Testing @WebMvcTest for a Controller 似乎在上下文中加载其他控制器
- @WebMvcTest 失败并出现 java.lang.IllegalStateException: Failed to load ApplicationContext
- @WebMvcTest 出于某种原因创建了多个控制器
- 带有@WebMvcTest 的测试切片正在加载大量与目标无关的控制器
这是我发现相关的代码部分
@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
这非常乏味。
我在这里错过了什么吗?
解决方案
在仔细查看您的ComplaintController
时,您使用@ControllerAdvice
Javadoc 对@WebMvcTest
作为测试的 Spring Context 一部分的相关 MVC bean 进行了以下说明:
/**
* Annotation that can be used for a Spring MVC test that focuses <strong>only</strong> on
* Spring MVC components.
* <p>
* Using this annotation will disable full auto-configuration and instead apply only
* configuration relevant to MVC tests (i.e. {@code @Controller},
* {@code @ControllerAdvice}, {@code @JsonComponent},
* {@code Converter}/{@code GenericConverter}, {@code Filter}, {@code WebMvcConfigurer}
* and {@code HandlerMethodArgumentResolver} beans but not {@code @Component},
* {@code @Service} or {@code @Repository} beans).
* ...
*/
所以 any@ControllerAdvice
是这个 MVC 上下文的一部分,因此这是预期的行为。
要解决此问题,您可以将异常处理从您的异常处理中提取ComplaintController
到一个专用类中,该类确实依赖于任何其他 Spring Bean,并且可以在不模拟任何内容的情况下进行实例化。
PS:在您的问题WebMvcTest 尝试加载每个应用程序 Controller的标题中, all这个词具有误导性。
推荐阅读
- node.js - 从后端 api 获取图像并以角度显示
- python - 将 csv 文件中的点绘制到 geopandas 地图上
- python - 当我连接两个字符串系列时,我可以强制 Python 仅以字符串格式返回吗?
- c# - 将方法的结果设置为变量我可以以文本字段形式返回 c#
- javascript - 更新其他对象内对象的状态,React js
- elasticsearch - 如何使用范围在kibana中获得一周的第一天?
- php - php从另一个数组创建关联数组
- python - 用 Python 替换 Facebook 帖子的图像
- tensorflow - 在 Tensorflow/Keras 中使用一种损失函数和度量另一种损失函数的目的?
- javascript - 刷新后如何保持 DOM 上的 JS 变化?