How to add Test Resources Root in Gradle/IntelliJ

2019-02-23 17:57发布

问题:

Using IntelliJ 14 and the 'idea' plugin in Gradle 2.2 for generating IntelliJ projects. I'm able to add a new Test Sources Root for integration tests in the following way:

idea {
    module {
        testSourceDirs += file('src/integrationTest/java')
    }
}

However, I have not found a way to add a corresponding Test Resources Root located at 'src/integrationTest/resources'. Any ideas on how to do this? Many thanks in advance.

-Daniel

回答1:

This should work :)

idea { 
    module.iml.withXml {
        def node = it.asNode()
        def content = node.component.find { it.'@name' == 'NewModuleRootManager' }.content[0]
        content.sourceFolder.each { sourceFolder ->
            if(sourceFolder.@url?.endsWith('/resources')) {
                sourceFolder.attributes().with {
                    boolean isTestSource = (remove('isTestSource') == 'true')
                    put('type', isTestSource ? 'java-test-resource' : 'java-resource')
                }
            }
        }
    }
}


回答2:

Just went through this trying to use the Cucumber plugin. The plugin correctly marks the src/cucumber/java and src/cucumber/groovy but not src/cucumber/resources, so the IntelliJ cucumber support gets confused. Played around with the above suggestions and this is working now:

idea {
    // Workaround to make sure the cucumber resources folder is
    // marked as "Test Resource Root" in IntelliJ. Otherwise the
    // IntelliJ cucumber integration gets confused wrt looking
    // up step definitions, highlighting, etc.
    module {
        testSourceDirs += file('src/cucumber/resources')
    }
    module.iml.withXml {
        def node = it.asNode()
        def content = node.component.find { it.'@name' == 'NewModuleRootManager' }.content[0]

        def cucumberSources = content.sourceFolder.findAll { it.@url?.contains('/src/cucumber/resources') }
        cucumberSources.each {
            it.@type = 'java-test-resource'
        }
    }
}