Mobile Development 2 min read

Recursive Login Handling in Android UiAutomator for Automated Testing

To avoid test failures caused by being logged into an unintended account, the author implements a recursive login routine in an Android UiAutomator script that checks the current user, logs out if necessary, and re‑logs in with the correct credentials, illustrating a concise and reusable testing solution.

FunTester
FunTester
FunTester
Recursive Login Handling in Android UiAutomator for Automated Testing

When performing automated testing, the author encountered failures caused by being logged in with an unexpected account, so they added a recursive login check to ensure the correct user is logged in before proceeding.

The following Java method using UiAutomator demonstrates this approach, recursively logging out and logging in with the desired credentials if the current account does not match the expected phone numbers:

public void login() throws UiObjectNotFoundException {
    clickMe(); //点击我的
    if (getUiObjectByResourceId("com.gaotu100.superclass:id/mylexuefragment_user_phone").exists()) {
        String id = getTextByResourceId("com.gaotu100.superclass:id/mylexuefragment_user_phone");
        if (id.contains("132249") | id.contains("157568")) {
            return;
        } else {
            exitApp();
            login();
        }
    } else {
        getUiObjectByResourceId("com.gaotu100.superclass:id/login_username").clearTextField();
        pressTimes(KeyEvent.KEYCODE_FORWARD_DEL, 12); //清除已有帐号
        getUiObjectByResourceId("com.gaotu100.superclass:id/login_username").setText("13120454218"); //输入帐号
        getUiObjectByResourceId("com.gaotu100.superclass:id/login_password").setText("qqqqqq"); //输入密码
        getUiObjectByResourceId("com.gaotu100.superclass:id/login_button").clickAndWaitForNewWindow(); //点击登录
    }
}

The same logic can be applied using Selenium for web testing, though the code is omitted here.

Readers are invited to view the original article and join a QQ group for further discussion.

AndroidUI AutomationTestingloginUiAutomatorRecursive Function
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.