Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 202
Evgenii Avatar asked Dec 14 '22 11:12

Evgenii


1 Answers

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)
like image 160
silyevsk Avatar answered Apr 30 '23 02:04

silyevsk