You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IntelliJ中分层Gradle项目的ScalaTest默认工作目录问题

ScalaTest Default Working Directory in Gradle Multi-Project Setup

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’s test task runs with its own project directory as the base, and the com.github.maiflai.scalatest plugin inherits this default since it builds on Gradle’s core Test task.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:56:27