How to let the app know if it's running Unit tests in a pure Swift project?

后端 未结 15 718
借酒劲吻你
借酒劲吻你 2021-01-30 05:08

One annoying thing when running tests in Xcode 6.1 is that the entire app has to run and launch its storyboard and root view controller. In my app this runs some server calls th

15条回答
  •  孤街浪徒
    2021-01-30 05:32

    The method I had been using stopped working in Xcode 12 beta 1. After trying all of the build based answers to this question, I was inspired by @ODB's answer. Here is a Swift version of a fairly simple solution that works for both Real Devices and Simulators. It should also be fairly "release proof".

    Insert in Test setup:

    let app = XCUIApplication()
    app.launchEnvironment.updateValue("YES", forKey: "UITesting")
    app.launch()
    

    Insert in App:

    let isTesting: Bool = (ProcessInfo.processInfo.environment["UITesting"] == "YES")
    

    To use it:

        if isTesting {
            // Only if testing
        } else {
            // Only if not testing
        }
    

提交回复
热议问题