我的应用程序有两个 Controller 。它们的结构如下所示:
@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
。我有一个 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;
...但这似乎不太可持续。随着我添加越来越多的 Controller ,我将有越来越多的不相关的 beans 污染我的测试。
我是否缺少注释或配置?或者我完全滥用了@WebMvcTest
?
最佳答案
尝试按如下方式指定被测 Controller :
@WebMvcTest(UsersController.class)
通过指定 none,您将告诉 Spring 所有 @Controller
bean 都应添加到应用程序上下文中,从而导致您得到的 UnsatisfiedDependencyException
。
关于spring-boot - @WebMvcTest 需要模拟与测试无关的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69338294/