2

I´m trying to add a new environment variable in my test but I see that

sys.env

is an immutable map, so I cannot see a way to add a new env var.

Any idea how?

paul
  • 12,873
  • 23
  • 91
  • 153

2 Answers2

3

The code you are testing should not depend on sys.env directly. Make environment: Map[String, String] a parameter - then you can pass any data you want in for testing, while still using sys.env in production.

Dima
  • 39,570
  • 6
  • 44
  • 70
  • But how do you expect to test my feature that use sys.env.getOrElse("HOST", "http://localhost:9083") I want to prove that not only the default value but a set env var works here – paul Jan 11 '18 at 11:42
  • That's what I am saying: your feature should not be using `sys.env`. It should take a configuration map as a parameter. Then, in the test, you can just pass `Map("HOST" -> "foobar")` to test it. – Dima Jan 11 '18 at 13:11
  • ok to test it as unit test is fine, but I was doing an integration test, but I get what you mean. – paul Jan 11 '18 at 13:21
  • 2
    Still I´m curious how to do add a new env var with scala – paul Jan 11 '18 at 13:21
  • For integration test, you set the environment outside of the process, before running the test. You cannot modify environment in scala or in java. Even if it was possible, it would be a very wrong thing to do. – Dima Jan 11 '18 at 13:32
1

Although it's kind of a different question, I think this answer applies: You can't modify the current process' environment (i.e. it's read-only).

As Dima said, you can use a map to save the properties or, like the answer I mentioned suggests, use scala.util.Properties, which gives you access to the current env and allows you to set your own properties.

If using Properties is definitely not an option, and you really need to set some env vars for all the tests, maybe you can use SBT to do that, like this:

fork in Test := true
envVars in Test := Map("ENV_VAR" -> "value")

The fork part is essential. Otherwise, the tests will run in the current process and won't pick up the new env vars.

David Castillo
  • 4,266
  • 4
  • 23
  • 25