@WebMvcTest 需要模拟与测试无关的 beans

@WebMvcTest requires mocking beans unrelated to test

我的应用程序有两个控制器。它们的结构如下所示:

@RestController
public class BooksController {
    private final DataService dataService;
    private final LibraryBookService libraryBookService;

    public BooksController(DataService dataService, LibraryBookService libraryBookService) {
        this.dataService = dataService;
        this.libraryBookService = libraryBookService;
    }

}

@RestController
public class UsersController {
    private final DataService dataService;

    public UsersController(DataService dataService) {
        this.dataService = dataService;
    }
}

DataServiceLibraryBookService都是bean。他们之间没有依赖关系。

我正在尝试为 UsersController 编写测试,我正在使用 @WebMvcTest。我有一个用于 DataService 的 @MockBean,所以我可以模拟它的响应:

@WebMvcTest
class UsersControllerTest {

    @Autowired
    MockMvc mvc;

    @MockBean
    DataService dataService;

    @BeforeEach
    void resetMocks() {
        Mockito.reset(this.dataService);
    }
    // ...
}

然而,当我尝试 运行 时,我收到一条“应用程序无法启动”消息和一条警告,指出 BooksController 无法正确自动装配其依赖项,堆栈跟踪指向:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'booksController' defined in file [/path/to/my/project/target/classes/com/example/rest/BooksController.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.LibraryBookService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.LibraryBookService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

为什么我的 UserController 测试关心 BooksController 及其依赖项(或缺少)?我可以通过像这样为 BooksController 添加 MockBean 来解决这个问题:

@MockBean
BooksController ignored;

...但这似乎不太可持续。随着我添加越来越多的控制器,我将有越来越多这些不相关的 bean 污染我的测试。

是否缺少注释或配置?还是我完全滥用了 @WebMvcTest

尝试按如下方式指定被测控制器:

@WebMvcTest(UsersController.class)

通过指定 none,您告诉 Spring 所有 @Controller beans 都应该添加到应用程序上下文中,因此您得到的是 UnsatisfiedDependencyException