在 sbt 中为测试配置设置默认环境变量 [英] Set default env variable for test configuration in sbt

查看:71
本文介绍了在 sbt 中为测试配置设置默认环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在 build.sbt 中,我需要检查是否设置了 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

sbt test

在开发者机器上本地运行,无需显式设置 SCALA_ENV,它将始终使用测试环境配置

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

我试过了

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

然后在测试中的某个地方

And then later somewhere in tests

System.getenv("SCALA_ENV")

但它总是返回空...

推荐答案

我无法按照描述复制您的问题:

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

和测试代码:

import org.scalatest.FlatSpec

class TestEnv extends FlatSpec {

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

}

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

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 variables window.

这篇关于在 sbt 中为测试配置设置默认环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆