[英]Spring Boot Service using Jpa repository Testing
我想测试一个Spring @Service。
该服务具有使用JpaRepository自动连线的方法。
那就是简单服务的代码。
@Service
public class PersonneService {
@Autowired
PersonneRepository personneRepository;
public Personne createPersonne(Personne personne) {
return personneRepository.save(personne);
}
我正在尝试测试,但出现错误
Unsatisfed dependency expressed for the service.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.symit.gmah.emprunt.services.PersonneHandleService': Unsatisfied dependency expressed through field 'personneService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.symit.gmah.emprunt.services.PersonneService' available: expected at least 1 bean which qualifies as autowire candidate. .....
那是我测试的代码。
@RunWith(SpringRunner.class)
@DataJpaTest
public class PersonneHandleService {
@Autowired
PersonneService personneService;
@Test
public void PersonneServiceCreateTest() {
Personne personne = new Personne("John","Doe","43343");
personne = personneService.createPersonne(personne);
assertNotNull(personne.getId());
}
您能帮我解释一下我该怎么做。
谢谢
PS:我正在使用嵌入式H2数据库;
That is my configuration:
# Enabling H2 Console
spring.h2.console.enabled=true
jdbc.driverClassName=org.h2.Driver
#jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.url=jdbc:h2:~/gmahdb;DB_CLOSE_DELAY=-1
jdbc.username=sa
jdbc.password=sa
您仍然必须将服务添加到Spring上下文中。 现在,您仅设置JPA(实体和存储库)。
或者,您也可以只使用@SpringBootTest代替@DataJpaTest。 这将加载整个应用程序进行测试。 根据应用程序的依赖关系的大小和数量,这可能不是最佳方案。
从DataJpaTest的文档中:
可以与@RunWith(SpringRunner.class)结合使用的批注,用于典型的JPA测试。 当测试仅针对JPA组件时可以使用。 使用此注释将禁用完全自动配置,而是仅应用与JPA测试相关的配置。
和...
如果要加载完整的应用程序配置,但使用嵌入式数据库,则应考虑将@SpringBootTest与@AutoConfigureTestDatabase结合使用,而不要使用此注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.