Spring Boot简单测试遇异常求助,主程序数据库操作正常
我明白你遇到的困扰了:项目主程序能正常对MySQL执行CRUD操作,但运行测试类时却抛出异常,而且当前使用的是JDK 9。先把你的测试代码贴出来方便参考:
@RunWith(SpringRunner.class) @SpringBootTest(classes = Demo4Application.class) public class MyJPATests { @Autowired BoardService boardService; @Test public void contextLoads() throws Exception { assertEquals(2, 2); } }
因为你没提供具体的异常堆栈信息,我结合JDK 9 + Spring Boot测试的常见问题,给你几个排查方向和解决办法:
1. 先确认Spring Boot版本是否兼容JDK 9
Spring Boot直到2.1.x版本才正式支持JDK 9,如果你用的是2.0.x及以下的旧版本,大概率会出现兼容问题。打开你的pom.xml(或build.gradle),检查parent依赖的版本:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.18.RELEASE</version> <!-- 至少要2.1.x,推荐用更高的2.x稳定版 --> <relativePath/> </parent>
如果版本过低,直接升级到兼容JDK 9的版本再测试。
2. 处理JDK 9模块系统的限制
JDK 9引入了模块系统,这会给Spring依赖的反射机制带来阻碍——毕竟Spring大量通过反射扫描、实例化Bean。
情况一:项目包含module-info.java
需要在模块描述文件中开放Spring需要访问的包,比如实体类、Repository所在的包:
module your.project.module { requires spring.boot; requires spring.boot.autoconfigure; requires spring.data.jpa; // 开放实体类包给Spring核心、JPA等模块 opens com.your.entity.package to spring.core, spring.data.jpa, spring.orm; // 开放Repository包给Spring Data JPA opens com.your.repository.package to spring.data.jpa; // 导出Service包供测试类访问 exports com.your.service.package; }
情况二:未使用module-info.java
可以在构建配置中添加JVM参数,绕过模块系统的限制:
<!-- pom.xml中的插件配置 --> <build> <plugins> <!-- Spring Boot插件 --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <jvmArguments>--add-modules java.se.ee</jvmArguments> </configuration> </plugin> <!-- 测试插件(Maven Surefire) --> <plugin> <artifactId>maven-surefire-plugin</artifactId> <configuration> <argLine>--add-modules java.se.ee</argLine> </configuration> </plugin> </plugins> </build>
3. 检查测试依赖是否完整且版本匹配
确保spring-boot-starter-test依赖已正确引入,且版本和parent依赖一致:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
如果使用JUnit 5,注意Spring Boot 2.2+才默认支持JUnit 5;若你用的是2.1.x版本,需要手动添加JUnit 5的依赖:
<dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <scope>test</scope> </dependency>
4. 简化测试上下文配置
你的测试类中@SpringBootTest指定了classes = Demo4Application.class,其实如果Demo4Application在项目根包下,Spring会自动扫描组件,这个参数可以省略。另外,如果你只是测试JPA相关功能,用@DataJpaTest会更轻量——它只加载JPA相关的上下文,能减少加载出错的概率:
@RunWith(SpringRunner.class) @DataJpaTest public class MyJPATests { @Autowired BoardService boardService; @Test public void contextLoads() throws Exception { assertEquals(2, 2); } }
如果以上方法都没解决问题,你把具体的异常堆栈信息贴出来,我就能更精准地帮你定位问题了。
内容的提问来源于stack exchange,提问作者NyansusCoder

