How do you know if you're running unit tests when calling swift test

We sometimes need to write code that needs to take a different path when it's running within a unit test. For example:

if runningTests {
   return
} else {
   // do ordinary api calls
}

This is typically done by reading some environment variable like:

if ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil {
    // Code only executes when tests are running
}

This SO post shows a few other solutions.

These work when running tests from within Xcode or from xcodebuild, but they don't seem to work when running tests using swift test.

What's the correct way to detect at runtime if code is running from within a unit test when running swift test?

Actually, this does work:

let isRunningUnitTests = NSClassFromString("XCTest") != nil
Terms of Service

Privacy Policy

Cookie Policy