1 minute read

Managing credentials and environment variables within Xcode and XCTest

Credentials, what can be easier, right? Just get them from .env file or whatever and you’re good to go. Well, not so fast… not on iOS.

To be honest, it was a bit challenging to make it work from Xcode and from the Terminal at the same time. Passing credentials through the command-line only is not a problem at all, but as soon as you want to run these tests from Xcode it takes a ridiculous turn.

So, if you happen to be dealing with credentials in native tests on iOS, I’m afraid you’re limited to the following options:

  1. Hard-code credentials in the test code
  2. Pass credentials through a scheme or an xctestplan

Let’s pretend that the first option is not an option at all and jump straight to the second one.

Precondition

Create an environment variable in your xctestplan:

  1. Open the .xctestplan file
  2. Click on the Configurations tab
  3. Arguments section → Env Vars row → button
  4. Add a new variable with the name AWESOME_TOKEN and the value $(AWESOME_TOKEN)
xctestplan configurations in Xcode


Create a sample test that prints the value of our secret token:

import XCTest

class SampleTestCase: XCTestCase {

    func testToken() {
      let awesomeToken = ProcessInfo.processInfo.environment["AWESOME_TOKEN"]!
      print(awesomeToken)
      XCTAssertFalse(awesomeToken.isEmpty)
    }
}

How to manage it

in Xcode

  1. Create env.xcconfig file in your project
    • File → New → File… → Configuration Settings File
    • Type the name of the file: env.xcconfig
    • Choose the location of the file
    • Choose the target with your tests
  2. Attach env.xcconfig to the tests’ target
    • Click on your project name in the Project Navigator
    • Open Info tab
    • Expand the Debug configuration in the Configurations section
    • Add env.xcconfig file to the app target for UI tests or to the test target for Unit tests
    xctestplan configurations in Xcode
  3. Add the AWESOME_TOKEN variable to the env.xcconfig file

     AWESOME_TOKEN = 1234567890
    
  4. Add env.xcconfig file to .gitignore!
  5. Run the test 🤌

PS: you might want to share this file with your team so that they can run the tests as well.

on CI

  1. Create a secret variable in your CI (e.g.: GitHub Actions)
  2. Create an empty env.xcconfig file on the fly so that xcodebuild command doesn’t fail

     touch env.xcconfig
    
  3. Run the test 🤌

     xcodebuild test \
       -project "Sample.xcodeproj" \
       -scheme "Sample" \
       -destination "platform=iOS Simulator,name=iPhone 14" \
       AWESOME_TOKEN=${{ secrets.AWESOME_TOKEN }} | xcpretty
    

Updated: