SpringBootTest中Autowired注入Repository为空及找不到Bean的问题
解决Spring Boot集成测试中Repository注入失败问题
问题分析
你的测试类出现两个问题:一是初始状态下MyRepository注入为null,二是添加@RunWith(SpringRunner.class)后提示找不到该类型的bean。核心原因集中在Spring容器未正确扫描并创建Repository实例,同时存在代码小错误。
具体解决步骤
1. 修正测试类中的实体创建错误
测试代码里new Entity()是错误的,应改为new MyEntity(),也可以用Builder模式创建:
// 方式1:无参构造 MyEntity entity = new MyEntity(); // 方式2:Builder模式(推荐) MyEntity entity = MyEntity.builder().build();
2. 确保Spring能扫描到Repository和实体类
Spring Boot默认扫描主启动类所在包及其子包下的组件。如果MyRepository、MyEntity不在主启动类的包层级内,需手动指定扫描范围:
- 在主启动类或测试类上添加以下注解:
@EnableJpaRepositories(basePackages = "你的Repository所在包路径") @EntityScan(basePackages = "你的Entity所在包路径")
示例:若主启动类在com.example.app,Repository在com.example.repository,Entity在com.example.entity,则:
@SpringBootApplication @EnableJpaRepositories(basePackages = "com.example.repository") @EntityScan(basePackages = "com.example.entity") public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } }
3. 检查依赖是否完整
确保项目依赖中包含JPA、H2数据库和测试启动器,Maven示例(pom.xml):
<dependencies> <!-- Spring Boot JPA 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- H2 内存数据库(测试用) --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>test</scope> </dependency> <!-- Spring Boot 测试依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
4. 修正application.properties中的JPA配置
规范Spring Boot的JPA属性写法,避免兼容问题:
# 替换原hibernate.hbm2ddl.auto为spring前缀的属性 spring.jpa.hibernate.ddl-auto=create # 替换原hibernate.dialect为spring前缀的属性 spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
5. 简化测试类注解(可选)
Spring Boot 2.x及以上版本中,@SpringBootTest已默认集成@ExtendWith(SpringExtension.class),@RunWith(SpringRunner.class)也可省略,简化后的测试类:
@SpringBootTest @ActiveProfiles("test") @AutoConfigureMockMvc public class ApplicationIntegrationTest { @Autowired MockMvc mvc; @Autowired MyRepository myRepository; @Test public void givenCourses() throws Exception{ MyEntity entity = new MyEntity(); myRepository.save(entity); mvc.perform(get("/someOperation") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content() .contentTypeCompatibleWith(MediaType.APPLICATION_JSON)); } }
6. 排除Flyway干扰(如果不需要)
若暂时不需要Flyway数据库迁移,可注释掉相关配置,测试是否能正常启动:
# spring.flyway.validateMigrationNaming= true # spring.flyway.locations= classpath:db/migration/h2
内容的提问来源于stack exchange,提问作者javaDeveloper
相关产品推荐
相关产品推荐

