Search code examples
iosxcodexctestxcode-ui-testingui-testing

Straightforward yet isolated view controller UI testing in Xcode Simulator possible?


Is it possible to run UI tests with the Xcode Simulator, for example, by manually initiating a view controller from an XCTestCase? I'm familiar with configuring the environment for a test via NSProcessInfo (or ProcessInfo) in Swift, but I have a certain case where it'd really be easier just to show a single view controller and run a series of gestures on it... versus navigating to it under certain conditions.

While I could create another target to do that, and then UI tests for that, I was wondering if there was a simpler approach.


Solution

  • You cannot manually initialize a UIViewController (or any other UIKit class) in your XCTestCase Class and run UITests on it.

    Your UITest test code runs as a separate process, synthesizing events that UI in your app responds to. In other words, the code that you write in your UITests runs on a Test Runner App that interacts with the App that your testing. The Test Runner app can only interact with the main app's UI Elements. It cannot access the main app's code or view hierarchy directly. So you cannot add a UIViewController during a test.

    As you already mentioned in your question you could add another target that only shows the View Controller you want to test. But that does not sound very practical to me.

    Or (as you also mentioned) you could set XUIApplication().launchArguments in your UITest and present the ViewController directly on app start when the launch arguments have been set.