Preventing Code Execution While Running Tests from CLI for Swift Package
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
Subscribe to my newsletter
Read articles from Javal Nanda directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Javal Nanda
Javal Nanda
๐ Hi, I'm Javal Nanda, a Mobile Application Developer based in India. I've been in the world of mobile app development since 2010, and this blog is my space to share experiences and thoughts.