问题描述
build.sbt:
Z
应用程序.conf
scalaVersion := "2.13.5"
lazy val testSettings = Seq(
Test / javaoptions += "-Dconfig.resource=/test.conf"
)
libraryDependencies ++= Seq(
"org.scalatest" %% "scalatest" % "3.2.3" % Test,"com.typesafe" % "config" % "1.4.1"
)
test.conf
some-value = "value from application.conf file"
并且只有 1 个规范测试类:
SomeTestSpec:
some-value = "value from test.conf file"
当我运行测试失败时:
class SomeTestSpec extends AnyFlatSpec with Matchers {
val config: Config = ConfigFactory.load()
"some test" should "read and print from test.conf" in {
val value = config.getString("some-value")
println(s"value of some-value = $value")
value shouldBe "value from test.conf file"
}
}
为什么规范读取文件 "value from [application].conf file" was not equal to "value from [test].conf file"
ScalaTestFailureLocation: SomeTestSpec at (SomeTestSpec.scala:12)
Expected :"value from [test].conf file"
Actual :"value from [application].conf file"
而不是 application.conf
? build.sbt 有问题吗?:
test.conf
解决方法
最佳做法是将 application.conf
放入 src/main/resources/
以供常规使用,放入 src/test/resources/
以进行测试。在测试中,您将有 2 个具有不同值的 conf 文件。如果您不需要更改测试配置,您可以简单地在 main
中保留一个 conf 文件。
您不必使用 -Dconfig.resource
或 -Dconfig.file
为您的测试显式覆盖文件,因为从类路径加载资源将按您的预期工作,并且将使用您的测试配置. -D
选项主要用于运行时提供外部配置或一些复杂的构建场景。
如果您使用 -Dconfig.resource
或 -Dconfig.file
,请注意路径。 config.resource
只是一个文件名,即 application.conf
将作为资源加载,而 config.file
是绝对或相对文件路径。
如果您正在制作一个库,您可能会喜欢具有默认值的 reference.conf
文件和覆盖它们的 application.conf
。这也适用于您的场景,但会更加混乱,因为这不是目的或参考文件。
出于测试目的,只需使用 2 个 application.conf
文件。
此外,这里有一些在运行时覆盖配置的选项:
Overriding multiple config values in Typesafe config when using an uberjar to deploy。
Overriding configuration with environment variables in typesafe config
Scala environment ${USER} in application.conf
更多信息在这里:https://github.com/lightbend/config#standard-behavior