如何检查 Spring 引导单元测试中的 WebMvcTest 是否加载了预期的控制器

How to check intended controllers are loaded in WebMvcTest in Spring Boot Unit Test

我的 Spring 启动应用程序中有多个控制器。我已经使用 @WebMvcTest 编写了 UnitTest 而没有定义特定的控制器 class。如何检查在当前 UnitTest 上下文

中加载的控制器 class

当你在 运行 @WebMvcTest 时得到一个 Spring 测试上下文,你可以尝试注入你的控制器(它们也是 Spring Beans)或者检查是否bean 存在于 WebApplicationContext.

以下测试使用了这两种方法:

@WebMvcTest(MyController.class)
class MyControllerTest {

  @Autowired
  private MockMvc mockMvc;

  @Autowired(required = false)
  private OtherController otherController;

  @Autowired(required = false)
  private MyController myController;

  @Autowired
  private WebApplicationContext webApplicationContext;

  @Test
  void test() throws Exception {

    assertNull(otherController);
    assertNotNull(myController);

    assertNotNull(webApplicationContext.getBean(MyController.class));
    assertThrows(NoSuchBeanDefinitionException.class, () -> webApplicationContext.getBean(OtherController.class));

  }
}

您还可以从 @Autowired 中删除 required=false,然后您的测试将立即失败,因为它无法注入请求的控制器 bean。