【问题标题】:WebMvcTest attempts to load every application ControllerWebMvcTest 尝试加载每个应用程序控制器
【发布时间】:2021-02-19 18:52:20
【问题描述】:

当我尝试实现 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 的每个依赖项,这非常乏味。
我在这里遗漏了什么吗?

【问题讨论】:

  • 请为你的AbstractTest类添加代码
  • @rieckpil 我已经更新并包含了AbstractTest

标签: java spring spring-test-mvc


【解决方案1】:

在仔细查看您的 ComplaintController 时,您使用 @ControllerAdvice 对其进行注释

@WebMvcTest 的 Javadoc 对作为 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).
 * ...
 */

因此,任何@ControllerAdvice 都是此 MVC 上下文的一部分,因此这是预期的行为。

要解决此问题,您可以将您的异常处理从您的 ComplaintController 提取到一个专用类中,该类确实依赖于任何其他 Spring Bean,并且可以在不模拟任何内容的情况下进行实例化。

PS:all 一词在您的问题标题中具有误导性WebMvcTest 尝试加载每个应用程序控制器

【讨论】:

  • 这就是我所缺少的,它就像一个魅力,谢谢。
猜你喜欢
  • 2021-03-01
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-04
  • 1970-01-01
相关资源
最近更新 更多