【问题标题】:Reading configuration files from unit tests从单元测试中读取配置文件
【发布时间】:2021-08-01 04:34:52
【问题描述】:

我有一个非常简单的项目。

build.sbt:

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"
)

resources文件夹下的两个配置文件:

应用程序.conf

some-value = "value from application.conf file"

test.conf

some-value = "value from test.conf file"

而且只有 1 个规格测试类:

一些测试规范:

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 而不是test.conf? build.sbt 有什么问题吗?:

lazy val testSettings = Seq(
  Test / javaOptions += "-Dconfig.resource=/test.conf"
)

【问题讨论】:

  • 尝试删除整个 testSettings 并将此 Test / javaOptions += "-Dconfig.resource=/test.conf" 留在顶层。
  • 我这样做了,但我得到了相同的结果,规范仍然是从 application.conf 而不是 test.conf ...
  • test.conf 移动到src/test/resources/application.conf 怎么样?
  • 是的,它奏效了。但我的问题仍然是Test / javaOptions += "-Dconfig.resource=/test.conf" 的这条线是什么?因为规范是从 application.conf(src/test/resources/application.conf)而不是test.conf-Dconfig.resource=/test.conf)中读取的
  • 不,在那种情况下根本不需要这条线,不知道为什么它不起作用或根本不应该起作用。

标签: scala scalatest typesafe-config


【解决方案1】:

最佳做法是将application.conf 放入src/main/resources/ 以进行常规使用,并将src/test/resources/ 放入以进行测试。您将在测试中有 2 个具有不同值的 conf 文件。如果您不需要更改配置进行测试,您只需在main 中保留一个配置文件即可。

您不必为您的测试显式地使用-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

【讨论】:

  • 非常感谢,您阐明了如何读取配置文件。现在有些事情对我来说是有意义的。
  • 非常感谢,您阐明了如何读取配置文件。现在有些事情对我来说是有意义的。
猜你喜欢
  • 2013-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-12
  • 2017-04-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多