我的應用程式有兩個控制器。它們的結構如下所示:
@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有豆類。它們彼此之間沒有依賴關系。
我正在嘗試為 UsersController 撰寫測驗,并且我正在使用@WebMvcTest. 我有一個@MockBeanDataService ,所以我可以模擬它的回應:
@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完全濫用了?
uj5u.com熱心網友回復:
嘗試按如下方式指定被測控制器:
@WebMvcTest(UsersController.class)
通過指定 none,您告訴 Spring 所有@Controllerbean 都應該添加到應用程式背景關系中,因此UnsatisfiedDependencyException您將獲得。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/328957.html
