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

时间:2019-10-03 13:30:33

标签: java spring spring-boot dependency-injection junit4

我有一个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:       没有可用的类型为io.clouding.repository.HostelRepository的合格Bean:预期位于   至少1个符合自动装配候选条件的bean。相依性   注释:{}

并在应用程序上:

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

2 个答案:

答案 0 :(得分:1)

我希望您的问题是您的豆HostelRespository未被创建。这是CouchbaseRepository。我希望它也不会在非测试环境中创建。

您要做的是,

@EnableJpaRepositories("io.clouding.repository")

添加

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

它将帮助运行时为您创建bean。因此,您的特定问题将得到解决。

注意

请注意,如果您仍未配置spring-data-couchbase所需的基础配置,则在解决此问题后可能还会看到其他错误,必须按照配置进行修复。您可以参考this

答案 1 :(得分:0)

错误说明,您可能有一个RequestRepository并且错误在其中;检查其中的构造函数/依赖项,看看是否没有注入某些东西或 显示 RequestRepository和完整的错误堆栈跟踪。

相关问题