'How to mock ProcessInfo / environment variables for swift executable

I'm trying to make a swift command line tool and have a helper function that checks for environment variables. But how can I unit test this function / mock ProcessInfo?

func withEnv(_ key: String) -> String {
    guard let value = ProcessInfo.processInfo.environment[key] else {
        print("Missing environment variable: \(key)")
        exit(1)
    }
    return value
}


Solution 1:[1]

In my opinion the best solution is to separate

  • your logic of parsing / returning the environment data.
  • retrieving the environment from ProcessInfo.processInfo.environment.

I.e.:

// You may add 1 test case just for "default" value of the 
// `ProcessInfo.processInfo.environment` 
// (to ensure it didn't change)
// Or skip testing this function all together
func withEnv(_ key: String) -> String {
    return withEnv(key, from: ProcessInfo.processInfo.environment)
}

// This function can be testing with all the possibilities for the environment
// present, missing, empty string etc.
func withEnv(_ key: String, from environment: [String: String]) -> String {
    guard let value = environment[key] else {
        print("Missing environment variable: \(key)")
        exit(1)
    }
    return value
}

// For example:
func testWithEnv() {

    let key = "someKey"
    let value = "abc"
    let environment: [String: String] = [
        key: value
    ]

    let actualEnv = withEnv(key, from: environment)
    XCTAssertEquals(value, actualValue)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1