【发布时间】:2021-11-19 02:41:47
【问题描述】:
我的应用程序有两个控制器。它们的结构如下所示:
@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;
}
}
DataService 和 LibraryBookService 都是 bean。它们之间没有依赖关系。
我正在尝试为 UsersController 编写测试,我正在使用 @WebMvcTest。我有一个 @MockBean 用于 DataService,所以我可以模拟它的响应:
@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?
【问题讨论】:
标签: spring-boot spring-mvc spring-boot-test