![](/img/trans.png)
[英]NoSuchBeanDefinitionException: No qualifying bean of type '<package>' available: expected at least 1 bean which qualifies as autowire candidate
[英]No qualifying bean of type 'Package.TestDaoRepo' available: expected at least 1 bean which qualifies as autowire candidate
嘿,我的 Web 應用程序使用的是 Spring Boot 2.3.4 版。 我正在編寫一個 JUNIT 集成測試用例,用於使用 WebMvcTest 測試我的控制器、服務和 Repo。
@ExtendWith(SpringExtension.class)
@WebMvcTest(TestCotroller.class)
class ITTestController {
@Test
void test() {
System.out.println("Test me ");
// URL to call. controller and rest of the logic
}
}
我正在尋找要加載的最低配置,因此我使用了 @WebMvcTest。
這是我的控制器需要測試
@RestController
@RequestMapping(value = APIUrlConstants.VERSION + APIUrlConstants.TEST_CONTROLLER)
public class TestCotroller {
@Autowired
TestServiceInf testServiceInf;
@RequestMapping(value = APIUrlConstants.TEST_DB, method = RequestMethod.GET)
public ResponseEntity<String> testDbStatus() {
Long count = testServiceInf.testDbStatus();
String responseMessage = "DB is up and running, total number of products count are -- " + count;
return new ResponseEntity<String>(responseMessage, HttpStatus.OK);
}
@RequestMapping(value = APIUrlConstants.TEST_APPLICATION, method = RequestMethod.GET)
public ResponseEntity<String> testApplicationStatus() {
String responseMessage = testServiceInf.testApplication();
return new ResponseEntity<String>(responseMessage, HttpStatus.OK);
}
}
服務類
@Service
public class TestServiceImpls implements TestServiceInf {
@Autowired
TestDaoRepo testDaoRepo;
private static String responseMessage = "Application is up and running";
@Override
public Long testDbStatus() {
Long countProduct = testDaoRepo.count();
System.out.println(countProduct);
return countProduct;
}
@Override
public String testApplication() {
return responseMessage;
}
}
回購類
@Repository
public interface TestDaoRepo extends JpaRepository<CpcMasterProduct, Long> { }
這是我面臨的錯誤 -
沒有可用的“package.TestDaoRepo”類型的合格 bean:預計至少有 1 個 bean 有資格作為自動裝配候選。 依賴注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
請幫助我哪里做錯了?
@WebMvcTest
不會實例化@Repository
豆。 這樣做是為了使測試更輕量級並隔離控制器測試。 通常,您會用模擬來替換您的服務以進行此類測試。
請參閱文檔以獲取解釋。
在您的情況下,您的測試將包含以下內容:
@ExtendWith(SpringExtension.class)
@WebMvcTest(TestCotroller.class)
class ITTestController {
@MockBean
private TestServiceInf serviceMock;
@Test
void test() {
System.out.println("Test me ");
// URL to call. controller and rest of the logic
}
}
如果要進行集成測試,則不應使用@WebMvcTest
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.