首页 > 解决方案 > WebMvcTest 尝试加载每个应用程序控制器

问题描述

当我尝试实现 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这非常乏味。
我在这里错过了什么吗?

标签: javaspringspring-test-mvc

解决方案


在仔细查看您的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这个词具有误导性。


推荐阅读