使用@DataJpaTest测试Repository时@Autowired注入失败问题
尝试使用@DataJpaTest对Repository进行测试,但@Autowired无法正常注入。已查找JUnit5结合@DataJpaTest的示例但未找到合适方案,添加其他依赖也无效,使用@SpringTest可正常工作,但希望使用@DataJpaTest。
测试代码:
package com.projetoSpring.catalog.repositories; import com.projetoSpring.catalog.model.Product; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import java.util.Optional; @DataJpaTest public class ProductRepositoryTests { @Autowired private ProductRepository repositorys; @Test public void deleteShouldDeleteObjectWhenIdExists() { long exintingId = 1L; repositorys.deleteById(exintingId); Optional<Product> result = repositorys.findById(1L); Assertions.assertFalse(result.isPresent()); } }
报错信息:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.projetoSpring.catalog.repositories.ProductRepositoryTests': Unsatisfied dependency expressed through field 'repositorys'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.projetoSpring.catalog.repositories.ProductRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
解决思路
确认ProductRepository的定义规范:确保该接口继承自Spring Data JPA的标准Repository接口(如
JpaRepository或CrudRepository),示例:public interface ProductRepository extends JpaRepository<Product, Long> { // 自定义方法(如果有) }@DataJpaTest只会自动识别并创建这类继承了Spring Data Repository接口的代理Bean,若未继承则无法被扫描到。检查包扫描范围:
@DataJpaTest默认扫描测试类所在包及其子包的Repository与实体类。若ProductRepository或Product实体在其他包,需通过basePackages属性指定扫描范围:@DataJpaTest(basePackages = {"com.projetoSpring.catalog.repositories", "com.projetoSpring.catalog.model"})验证依赖完整性:确保项目中已正确引入
spring-boot-starter-data-jpa和spring-boot-starter-test依赖,无需额外添加JUnit5相关依赖(spring-boot-starter-test已包含JUnit5核心组件)。Maven依赖示例:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>检查主应用类的包层级:若项目的主启动类(标注
@SpringBootApplication的类)不在com.projetoSpring或更上层包,需通过@DataJpaTest的baseClasses属性指定主启动类,确保Spring能正确扫描组件:@DataJpaTest(baseClasses = YourSpringBootApplication.class)排查自定义配置冲突:若项目中有自定义JPA配置类,确保该配置类被
@DataJpaTest扫描到;或者使用@AutoConfigureTestDatabase指定测试用数据库(@DataJpaTest默认自动配置H2内存数据库,若自定义数据源可能导致冲突):@DataJpaTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) // 若使用自定义测试数据库
内容的提问来源于stack exchange,提问作者Pedro Henrique

