您可以构建自己的解析器或使用 Groovy 的内置 JSON 解析器:
package de.scrum_master.stackoverflow
import groovy.json.JsonParserType
import groovy.json.JsonSlurper
import spock.lang.Specification
class FileRecursionTest extends Specification {
def jsonDirectoryTree = """{
com : {
na : {
tests : [
MyBaseIT.groovy
]
},
twg : {
sample : {
model : [
PrimeNumberCalculatorSpec.groovy
]
}
}
},
de : {
scrum_master : {
stackoverflow : [
AllowedPasswordsTest.groovy,
CarTest.groovy,
FileRecursionTest.groovy,
{
foo : [
LoginIT.groovy,
LoginModule.groovy,
LoginPage.groovy,
LoginValidationPage.groovy,
User.groovy
]
},
LuceneTest.groovy
],
testing : [
GebTestHelper.groovy,
RestartBrowserIT.groovy,
SampleGebIT.groovy
]
}
}
}"""
def "Parse directory tree JSON representation"() {
given:
def jsonSlurper = new JsonSlurper(type: JsonParserType.LAX)
def rootDirectory = jsonSlurper.parseText(jsonDirectoryTree)
expect:
rootDirectory.de.scrum_master.stackoverflow.contains("CarTest.groovy")
rootDirectory.com.twg.sample.model.contains("PrimeNumberCalculatorSpec.groovy")
when:
def fileList = objectGraphToFileList("src/test/groovy", rootDirectory)
fileList.each { println it }
then:
fileList.size() == 14
fileList.contains("src/test/groovy/de/scrum_master/stackoverflow/CarTest.groovy")
fileList.contains("src/test/groovy/com/twg/sample/model/PrimeNumberCalculatorSpec.groovy")
}
List<File> objectGraphToFileList(String directoryPath, Object directoryContent) {
List<File> files = []
directoryContent.each {
switch (it) {
case String:
files << directoryPath + "/" + it
break
case Map:
files += objectGraphToFileList(directoryPath, it)
break
case Map.Entry:
files += objectGraphToFileList(directoryPath + "/" + (it as Map.Entry).key, (it as Map.Entry).value)
break
default:
throw new IllegalArgumentException("unexpected directory content value $it")
}
}
files
}
}
请注意:
我使用new JsonSlurper(type: JsonParserType.LAX)
它是为了避免在 JSON 结构中引用每个字符串。如果你的文件名包含空格或其他特殊字符,你将不得不使用类似的东西"my file name"
。
在rootDirectory.de.scrum_master.stackoverflow.contains("CarTest.groovy")
您可以看到如何在.property
语法中很好地与解析的 JSON 对象图进行交互。你可能喜欢与否,需要与否。
递归方法objectGraphToFileList
将解析的对象图转换为文件列表(如果您更喜欢一个集合,请更改它,但File.eachFileRecurse(..)
不应产生任何重复项,因此不需要该集合。
如果您不喜欢 JSON 中的括号等,您仍然可以构建自己的解析器。
您可能想要添加另一种实用程序方法来从经过验证的目录结构中创建类似于给定字符串的 JSON 字符串,这样您在编写类似测试时的工作量就会减少。