I have an app with a login system, so once user have logged in the app, I store their session in a local DB, which prevents users to have log in every time they use the app. Obviously, if users have not logged in, the app displays a LoginViewController
, but if the app detects a current session for the user, a HomeViewController
is displayed.
I have created a few tests for my HomeViewController
and they all work fine. However, I have realised they are working fine because the app currently has a session stored. If I enter the app and logout the current user, when I run the UI tests they will fail. This makes sense, as the test expects a HomeViewController
to be displayed, and instead the LoginViewController
is shown.
Considering that I would also like to create UI tests for the LoginViewController
, it seems reasonable to create a solution where, in each test, I set if the user is logged in or not. How can I do so?
After some research, found the answer at XCUIApplication
launch arguments/environments. This allows you to send certain configuration when executing the test that can be interpreted by your main code later.
For my case to work, I placed the following code:
// UI Test
func testWelcomeIsShown() {
let app = XCUIApplication()
app.launchArguments.append("isUITestingLogin")
app.launch()
// Rest of your test steps
}
// AppDelegate or wherever you fetch your current session
func getCurrentSession() {
if NSProcessInfo.processInfo().arguments.contains("isUITestingLogin") {
session = nil
} else {
session = DatabaseManager.getSession()
}
}
Note: This code will work for recording and executing your test. However, if you do have multiple tests with the same logic, you would probably move the first 3 lines of testWelcomeIsShown()
to the setUp()
of the test class. However, it is important to remember that this setup is not executed when recording the test, so you need to manually set a no current session environment.
You could alternatively use SBTUITestTunnel which among other things allows you to upload a file from your test target to the app's sandbox. It should be enough to prepare a DB with prefilled login informations which then gets sent to the apps' target on startup.
The beauty of the library is that the app's code isn't polluted with test code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With