tallariel
(Ariel Elkin)
1
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?
tallariel
(Ariel Elkin)
2
Actually, this does work:
let isRunningUnitTests = NSClassFromString("XCTest") != nil
1 Like
mvolkmann
(Mark Volkmann)
3
This doesn't work for me. I need nil from NSClassFromString("XCTest") even when running in an XCTest.
Mordil
(Nathan Harris)
4
I think in Swift 5.6 this works properly
#if canImport(XCTest)
return
#else
// do ordinary api calls
#endif
The downside being that you don't get compiler support for that else branch unless you're building in release configuration...
1 Like