gpt4 book ai didi

java - 使用 Jpa 存储库测试的 Spring Boot 服务

转载 作者:行者123 更新时间:2023-12-02 11:20:51 25 4
gpt4 key购买 nike

我想测试 Spring @Service。

此服务具有使用 JpaRepository Autowiring 的方法。

这是简单服务的代码。

@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的文档:

Annotation that can be used in combination with @RunWith(SpringRunner.class) for a typical JPA test. Can be used when a test focuses only on JPA components. Using this annotation will disable full auto-configuration and instead apply only configuration relevant to JPA tests.

还有...

If you are looking to load your full application configuration, but use an embedded database, you should consider @SpringBootTest combined with @AutoConfigureTestDatabase rather than this annotation.

关于java - 使用 Jpa 存储库测试的 Spring Boot 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49924562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com