Preventing Code Execution While Running Tests from CLI for Swift Package

Preventing Code Execution While Running Tests from CLI for Swift Package

ยท

1 min read

Ideally, you would not require conditional logic in your production code to check if tests are running or the main app target is running. But, there are situations where you can't get around it in case of Integration tests or UI Tests.

There are various solutions which you might have come across such as:

var isRunningTests: Bool {
    return ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil
}

// Usage
if isRunningTests {
} else {
}

Or setting your own environment variable for the test scheme/configuration and check it as below:

var isRunningTests: Bool {
    ProcessInfo.processInfo.environment["isRunningTest"] != nil 
}

While these solutions work fine for unit tests when running tests from Xcode (โŒ˜+ U), it does not work when running tests from command line for a swift package using following command: swift test

Solution:

While running tests from the command line, the name of the process that is getting executed is xctest . So, we can check if the current process is running tests as follows:

var isRunningTests: Bool {
    ProcessInfo.processInfo.processName == "xctest"
}

Let me know if you found this helpful. Feel free to tweet me on Twitter if you have any additional tips or feedback.

Thanks

ย