spring-boot - @WebMvcTest 需要模拟与测试无关的 bean

标签 spring-boot spring-mvc spring-boot-test

我的应用程序有两个 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;
    }
}

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;

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

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

最佳答案

尝试按如下方式指定被测 Controller :

@WebMvcTest(UsersController.class)

通过指定 none,您将告诉 Spring 所有 @Controller bean 都应添加到应用程序上下文中,从而导致您得到的 UnsatisfiedDependencyException

关于spring-boot - @WebMvcTest 需要模拟与测试无关的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69338294/

相关文章:

spring - 如何使用 Spring WebFlux 返回 404

java - 实体 save() 方法挂起且没有错误

spring-boot - lettuce客户端连接redis时出现内存泄漏错误

java.lang.VerifyError : in tomcat in fedora env 错误

spring-boot - 对于@SpringBootTest @TestConfiguration 类的@Import 什么都不做,而@ContextConfiguration 按预期覆盖

maven - 使用 Spring Boot 和嵌入式驱动程序测试 Neo4j

java - 让所有 Kubernetes Pod 监听同一个 Kafka 主题

html - 如何将默认值添加到 Thymeleaf 中的输入字段

java - spring-mvc 不会将我的请求参数绑定(bind)到 int

java - WireMock 有时表现得很奇怪