scala 在 sbt 中为测试配置设置默认环境变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37330416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 08:18:15  来源:igfitidea点击:

Set default env variable for test configuration in sbt

scalasbt

提问by Idon Lee

In my app i have runtime config initialization based on SCALA_ENV variable

在我的应用程序中,我有基于 SCALA_ENV 变量的运行时配置初始化

In build.sbt i need to check if SCALA_ENV var is set, and if not set it to "test" but only for tests configuration, so that when

在 build.sbt 中,我需要检查是否设置了 SCALA_ENV 变量,如果没有将其设置为“测试”,但仅用于测试配置,以便当

sbt test

is run locally on a developer machine without explicitly setting SCALA_ENV it would always use test environment configs

在开发人员机器上本地运行而不显式设置 SCALA_ENV 它将始终使用测试环境配置

I tried

我试过

fork in test := true
envVars in Test := Map("SCALA_ENV" -> "test")

And then later somewhere in tests

然后在测试的某个地方

System.getenv("SCALA_ENV")

But it always returns null...

但它总是返回空...

回答by Vitalii Kotliarenko

I cannot reproduced you issue as desribed:

我无法按照所描述的那样重现您的问题:

//build.sbt
name := "test-env"

version := "1.0"

scalaVersion := "2.11.8"

fork in Test := true

envVars in Test := Map("SCALA_ENV" -> "test")

libraryDependencies ++= Seq("org.scalactic" %% "scalactic" % "2.2.6", "org.scalatest" %% "scalatest" % "2.2.6" % "test")

And test code:

和测试代码:

import org.scalatest.FlatSpec

class TestEnv extends FlatSpec {

  it should "get the correct env var value" in {
    assert("test" === System.getenv("SCALA_ENV"))
  }

}

If I run it with sbt test, it passes. Note, I use sbt 0.13.8, so if your version differs, you may face some wild bug. When I run it from IntelliJ Idea - it fails, and there is no wonder why - IDE uses its own test runner and skips sbt. As a workaround, you can set variable in Run/Debug Configurations-> Environment variableswindow.

如果我用 运行它sbt test,它就会通过。注意,我使用sbt 0.13.8,所以如果你的版本不同,你可能会遇到一些疯狂的错误。当我从 IntelliJ Idea 运行它时 - 它失败了,难怪为什么 - IDE 使用自己的测试运行程序并跳过 sbt。作为解决方法,您可以在Run/Debug Configurations->Environment variables窗口中设置变量。