IntelliJ中分层Gradle项目的ScalaTest默认工作目录问题
Let’s break down the default behavior and solutions tailored to your exact setup (Gradle 4.3, com.github.maiflai.scalatest plugin, root + subproject repo structure):
- By default, ScalaTest tests run under Gradle use the subproject’s root directory as their working directory. For example, tests in your
./compiler/subproject will have./compiler/as their working directory. This is standard Gradle behavior—each subproject’stesttask runs with its own project directory as the base, and thecom.github.maiflai.scalatestplugin inherits this default since it builds on Gradle’s coreTesttask.
This is why you’ll hit issues trying to access root-repo files from subproject tests: a relative path like ./input.txt will look for ./compiler/input.txt instead of the file actually stored at your repo’s root.
How to Resolve This (Two Practical Approaches)
1. Override the Test Task’s Working Directory
You can reconfigure the working directory to point to your repo’s root, either for all subprojects or just specific ones:
For all subprojects (add to your root build.gradle):
subprojects { tasks.withType(Test) { // Set working directory to the root of your entire repository workingDir = rootProject.projectDir } }
For a single subproject (add to ./compiler/build.gradle):
test { workingDir = rootProject.projectDir }
After this change, any relative paths in your ScalaTest code will resolve against the repo root, so ./input.txt will correctly target the file at your repository’s top level.
2. Pass the Repo Root Path as a System Property
If you don’t want to change the working directory (e.g., some tests rely on the subproject directory), you can pass the repo root path directly to your tests via a system property:
First, add this to your root or subproject build.gradle:
test { systemProperty "repoRootDir", rootProject.projectDir.absolutePath }
Then, retrieve the path in your ScalaTest code to load files:
import java.io.File class CompilerSpec extends AnyFunSpec { val repoRoot = new File(System.getProperty("repoRootDir")) val testInputFile = new File(repoRoot, "test-input.txt") // Your test assertions here }
Verify the Working Directory
To confirm the working directory for your tests, add a quick debug line to one of your specs:
println(s"Current test working directory: ${new File(".").getAbsolutePath}")
Running your tests will output the exact directory your relative paths are resolving against.
内容的提问来源于stack exchange,提问作者Gabor Szarnyas

