我正在尝试编写集成测试,但在测试中自动装配存储库时遇到问题。如何在Spring Boot的集成测试中自动连接存储库?
我收到此异常: org.springframework.beans.BeanInstantiationException:无法实例化[org.observer.media.repository.ArticleRepository]:指定的类是一个接口。
编辑: 我在@EnableJpaRepositories中添加了PersistenceConfig.class,代码如下。这导致异常org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
我也尝试添加Application.class在@SpringBootTest(类= {}在包罗万象的尝试,但抛出Error creating bean with name 'articleRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class org.observer.media.model.Article
ScraperRunnerIntegrationTest(在配置类仅包含域类的豆) :
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {
ApplicationConfig.class,
PersistenceConfig.class,
DeMorgenTestConfig.class,
Article.class,
ScraperRunner.class,
DeMorgenWebsiteScraper.class,
ArticleService.class,
DeMorgenPageScraper.class,
JsoupParser.class,
DeMorgenArticleScraper.class,
GenericArticleScraper.class,
ImageMetaScraper.class,
ArticlePrinter.class,
ArticleRepository.class
})
public class ScraperRunnerIntegrationTest {
private final static Article EXPECTED_ARTICLE_1 = anArticle().withHeadline("headline1").build();
private final static Article EXPECTED_ARTICLE_2 = anArticle().withHeadline("headline2").build();
@Autowired
private ScraperRunner scraperRunner;
@Autowired
private DeMorgenWebsiteScraper deMorgenWebsiteScraper;
@Autowired
private ArticleRepository articleRepository;
@Test
public void run() {
scraperRunner.run(deMorgenWebsiteScraper);
assertThat(articleRepository.findAll()).containsOnly(EXPECTED_ARTICLE_1, EXPECTED_ARTICLE_2);
}
库:
import org.observer.media.model.Article;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ArticleRepository extends JpaRepository<Article, Long> {
List<Article> findAll();
Article findByHash(String hash);
Article findByHeadline(String headline);
List<Article> findArticleByHeadlineAndCompanyName(String headline, String companyName);
@Query("SELECT CASE WHEN COUNT(a) > 0 THEN true ELSE false END FROM Article a WHERE a.hash = :hash")
boolean existsByHash(@Param("hash") String hash);
}
PersistenceConfig.class:
package org.observer.media.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EnableJpaRepositories("org.observer.media.repository")
public class PersistenceConfig {
}
你有@ @ EnableJpaRepositories'注释在你的'@ Configuration'类吗? –
在此代码中没有明确定义。我已经尝试了这个注释,并在那一刻得出结论,它不是罪魁祸首,并且认为注释包含在SpringBootTest注解中。我可能是错的,但是当我在后面的代码在我面前时,会将注释放回原处。我相信它然后抱怨没有应该由Spring Boot自动配置的EntityManagerFactory我认为。然后我提供了一个配置数据源和emf等,然后它回到了同样的错误,在这篇文章中。 – progonkpa
@mp_loki我添加了注释EnableJpaRepositories,请参阅我在编辑 – progonkpa