Evgenii
Evgenii

Reputation: 37339

How to change app's NSProcessInfo environment dictionary from a unit test?

I have the following code in my app. Its behaviour can be altered by setting a "MY_KEY" key in its environment dictionary of its process information.

func myMethod() {
  var environment = NSProcessInfo.processInfo().environment
  if environment["MY_KEY"] { /* do something /* }
}

I would like to test this in a unit test. The problem is that changing the environment dictionary in the unit test does no affect the dictionary in the app.

class MyAppTests: XCTestCase {
  func testMe() {
    var environment = NSProcessInfo.processInfo().environment
    environment["MY_KEY"] = "my value"
    myMethod()
    // The app's environment does not change
  }
end

Is it possible to change the environment dictionary of the app from a unit test?

Upvotes: 6

Views: 2359

Answers (1)

silyevsk
silyevsk

Reputation: 4566

The environment provided by NSProcessInfo is read-only. You can set environment variable using setenv c function (works fine from Swift), like this:

setenv("MY_KEY", "my value", 1)

Upvotes: 16

Related Questions