繁体   English   中英

没有可用的“Package.TestDaoRepo”类型的合格 bean:预计至少有 1 个 bean 有资格作为自动装配候选

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM