Groovy项目遇MissingPropertyException:无法访问同包类sampleConstants
排查Groovy同包类访问的
MissingPropertyException问题 问题背景
作为Groovy初学者,在IntelliJ中构建示例项目并使用Spock编写sampleHelper类的测试时,运行createToken方法测试出现错误:
groovy.lang.MissingPropertyException: No such property: sampleConstants for class: com.tutorial.sampleHelper
确认同包类无需导入,且IDE中点击sampleConstants.TOKEN可跳转至正确文件,附上项目结构及代码寻求排查指引。
项目结构
└── sample-project ├── pom.xml ├── resources ├── src --> set as sources root │ └── com │ └── tutorial │ ├── sampleConstants.groovy │ └── sampleHelper.groovy └── tests --> set as tests root └── com └── tutorial └── sampleHelperSpec.groovy
相关代码
sampleHelper.groovy
package com.tutorial public class sampleHelper implements Serializable { Boolean enabled public sampleHelper(config) { this.enabled = config.enabled } def createToken() { def token = enabled ? "abc" : sampleConstants.TOKEN return token } }
sampleConstants.groovy
package com.tutorial public class sampleConstants { static final TOKEN = "cde" }
排查指引
显式导入同包类:虽然Groovy理论上同包类无需导入,但部分场景下(如Maven编译上下文、IDE类加载逻辑)可能需要显式导入。在
sampleHelper.groovy顶部添加导入语句:import com.tutorial.sampleConstants重新运行测试验证。
清除IntelliJ缓存并重启:IDE缓存异常可能导致“能跳转但编译报错”的矛盾情况。执行
File -> Invalidate Caches... -> 勾选Clear file system cache and local history -> 点击Invalidate and Restart,重启后重新编译项目。修正Maven目录结构与编译配置:当前项目结构不符合Maven标准(标准为
src/main/groovy存源码、src/test/groovy存测试代码),可能导致编译异常:- 调整目录结构,将源码移至
src/main/groovy/com/tutorial,测试代码移至src/test/groovy/com/tutorial; - 在
pom.xml中添加Groovy编译插件配置:<build> <plugins> <plugin> <groupId>org.codehaus.gmavenplus</groupId> <artifactId>gmavenplus-plugin</artifactId> <version>1.13.1</version> <executions> <execution> <goals> <goal>compile</goal> <goal>testCompile</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
执行
mvn clean compile test命令,通过Maven命令行验证是否能正常编译运行测试,排除IDE配置问题。- 调整目录结构,将源码移至
更换静态成员访问方式:尝试用方法调用的方式访问静态常量,替代直接属性访问:
def token = enabled ? "abc" : sampleConstants.getTOKEN()
内容的提问来源于stack exchange,提问作者user88659
相关产品推荐
相关产品推荐

