Search code examples
javaspringspring-bootdependency-injectionjunit4

SpringBoot : Testing a service with Constructor Dependency Injection


I have a SpringBoot app (REST Architecture ) I have this service defined that uses Constructor Dependency Injection

@Service
@Slf4j
public class HostelService {

    private final HostelRepository hostelRepository;

    HostelService(HostelRepository hostelRepository) {
        this.hostelRepository = hostelRepository;
    }
}

I want to use it in a integration test:

@RunWith(SpringRunner.class)
@SpringBootTest
public class HostelServiceIntegrationTest {

    public static final String Hostel_1 = "Hostel::1";

    @Autowired
    protected HostelRepository hostelRepository;

    @Autowired
    private HostelService hostelService;


    //...
}

@Repository
public interface HostelRepository extends CouchbaseRepository<Hostel, String> {

}

but I have this error:

..Unsatisfied dependency expressed through constructor parameter 0;

Caused by:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.clouding.repository.HostelRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

and on the Application:

@SpringCloudApplication
@SpringBootApplication
@EnableJpaRepositories("io.clouding.repository")
@ComponentScan(basePackages = { "io.clouding.repository" })
public class Application implements WebMvcConfigurer {
..
}

Solution

  • I hope your problem is that your bean, HostelRespository is not getting created. And it's a CouchbaseRepository. I hope it's not even created in non-test environment also.

    What you have to do is, instead of

    @EnableJpaRepositories("io.clouding.repository")
    

    add

    @EnableCouchbaseRepositories(basePackages = {"io.clouding.repository"})
    

    It will help run-time to create the bean for you. So your specific problem will be solved.

    Note:

    Please note that, if you haven't still configured the underlying configurations needed for spring-data-couchbase, you might see some other errors after fixing this, that you have to fix by configuration. You may refer this.