【问题标题】:@WebMvcTest requires mocking beans unrelated to test@WebMvcTest 需要模拟与测试无关的 bean
【发布时间】: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;
    }
}

DataServiceLibraryBookService 都是 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


    【解决方案1】:

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

    @WebMvcTest(UsersController.class)
    

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

    【讨论】:

    • 太棒了,谢谢——这完全成功了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    • 2022-01-23
    • 2014-08-15
    • 2015-02-05
    相关资源
    最近更新 更多