【问题标题】:No qualifying bean of type 'Package.TestDaoRepo' available: expected at least 1 bean which qualifies as autowire candidate没有可用的“Package.TestDaoRepo”类型的合格 bean:预计至少有 1 个有资格作为自动装配候选者的 bean
【发布时间】:2021-01-30 01:17:52
【问题描述】:

嘿,我正在为我的 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)}

请帮助我哪里做错了?

【问题讨论】:

    标签: java spring-boot


    【解决方案1】:

    @WebMvcTest 不会实例化 @Repository bean。这样做是为了使测试更轻量级并隔离控制器测试。通常,您会用模拟来替换您的服务以进行此类测试。

    请参阅docs 了解说明。

    在您的情况下,您的测试将包含以下内容:

    @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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-13
      • 1970-01-01
      • 2019-09-25
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多