Spring Boot:使用构造函数依赖注入测试服务

SpringBoot : Testing a service with Constructor Dependency Injection

我有一个 SpringBoot 应用程序(REST 架构) 我定义了使用构造函数依赖注入的服务

@Service
@Slf4j
public class HostelService {

    private final HostelRepository hostelRepository;

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

我想在集成测试中使用它:

@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> {

}

但是我有这个错误:

..Unsatisfied dependency expressed through constructor parameter 0;

原因:

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: {}

在应用程序上:

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

错误说明了,您可能有一个 RequestRepository,错误就在其中;检查其中的 constructor/dependencies 并查看是否未注入某些内容或 show RequestRepository 和完整的错误堆栈跟踪。

我希望你的问题是你的 bean HostelRespository 没有被创建。这是一个 CouchbaseRepository。我希望它甚至不是在非测试环境中创建的。

你要做的是,代替 of

@EnableJpaRepositories("io.clouding.repository")

添加

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

它将帮助 运行-time 为您创建 bean。所以你的具体问题将得到解决。

:

请注意,如果您还没有配置 spring-data-couchbase 所需的基础配置,您可能会在修复此问题后看到一些其他错误,您必须通过配置来修复这些错误。您可以参考 this.