英文:
Groovy/IntelliJ: groovy.lang.MissingPropertyException: No such property
问题
我是一名初学者,正在使用IntelliJ尝试构建一个样本项目并为类sampleHelper编写一些spock测试。
运行我的createToken方法的测试会导致以下错误:
groovy.lang.MissingPropertyException: No such property: sampleConstants for class: com.tutorial.sampleHelper
我的理解是同一包中的类无需导入。我一定是犯了一个愚蠢的错误,但不确定我哪里出错了。任何指针都将不胜感激。
从类中点击sampleConstants.TOKEN
确实会转到正确的文件。
我有以下文件夹结构:
└── sample-project
├── pom.xml
├── resources
├── src --> 设置为源目录
│ └── com
│ └── tutorial
│ ├── sampleConstants
│ └── sampleHelper
└── tests --> 设置为测试根目录
└── com
└── tutorial
└── sampleHelper
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"
}
英文:
I'm a groovy beginner and using IntelliJ trying to build a sample project and some tests in spock for the class sampleHelper.
Running my test for the method createToken results in the following error:
groovy.lang.MissingPropertyException: No such property: sampleConstants for class: com.tutorial.sampleHelper
My understanding is that classes in the same package do not need to be imported. I must be making a silly mistake but not sure where I'm going wrong. Any pointers are appreciated.
Clicking on sampleConstants.TOKEN
from the class does go to the correct file.
I have the following folder structure:
└── sample-project
├── pom.xml
├── resources
├── src --> set as sources root
│   └── com
│   └── tutorial
│   ├── sampleConstants
│   └── sampleHelper
└── tests --> set as tests root
└── com
└── tutorial
└── sampleHelper
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"
}
答案1
得分: 2
在Java(和Groovy)中,传统上类名以大写字母开头。
Groovy解析器有时会依赖于这一传统,如果您使用小写字母开头的类,它可能会难以理解您的意思,而是寻找具有该名称的字段或变量。
始终使用大写字母命名类名(以及包含它们的文件)是一个好主意,因为它可以避免像这样的情况(看起来像是世界疯了) 😉
英文:
Classes in Java (and Groovy) traditionally start with a capital letter.
The Groovy parser sometimes relies on this tradition, and if you use classes with lower-case letters, it struggles to see what you mean and instead looks for a field or variable with that name.
Always using a capital letter for class names (and the files that contain them) is always a good idea, as it saves you from things like this (which look like the world has gone mad) 😉
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论