How to Switch between webContext and native context before the method

Im performing testing against hybrid app and there are some scenarios the element locator are extracted from web context and some other from native app context

so i have created 1 page factory and two classes one for the native app and one for the web context
as shown in the sample below

so what i want to do is to set for example driver.context(“NATIVE_APP”); to be run before each method inside the class of native app

and to run driver.context(webContext); before each method inside the webcontext class

to avoid adding driver.context(…); before each method in both class also to be able to run Test that combine methods from both web and native class so each method will be called will automatically change to relevant context

i was struggling and tried to at annotation @BeforeMethod but no use

pageFactory decorator

public class Decorator extends BaseSetup {

protected WebDriverWait wait;
public Decorator(AppiumDriver<MobileElement> driver) {
    this.driver = driver;
    wait = new WebDriverWait(driver, 5);
    JavascriptExecutor executor = (JavascriptExecutor)driver;
    PageFactory.initElements(new AppiumFieldDecorator(driver),this);
}

}

native app class

public class LoginPage extends Decorator {

public LoginPage() {
    super(driver);
}

@BeforeMethod
public void context() {
    driver.context("NATIVE_APP");
}


@AndroidFindBy(xpath = "//android.widget.Button[....']")
private MobileElement element;

public void welcome_header_is_visible() {
    wait.until(ExpectedConditions.visibilityOf(welcomeHeader));
}

Wecontext

public class LoginPage extends Decorator {

public LoginPage() {
    super(driver);
}


@BeforeMethod
private void context() {
    driver.context("WEBVIEW_com.example.mobile");
}


@FindBy(xpath = "//h1[text()='Welcome to example!']")
private WebElement welcomeHeader;

public void Verify_visibility_of_welcome_header () {
    WebDriverWait wait = new WebDriverWait(driver, 10);
    wait.until(ExpectedConditions.visibilityOf(welcomeHeader));
}

@Aleksei can you please provide some ideas

use something like:

    protected boolean switchToWebContext() {
        ArrayList<String> contexts = new ArrayList(driver.getContextHandles());
        for (String context : contexts) {
            System.out.println(context);
            if (context.contains("WEBVIEW")) {
                driver.context(context);
                return true;
            }
        }
        return false;
    }

and in code better do switch with element needed in web:

public void Verify_visibility_of_welcome_header () {
    switchToWebContext();
    WebDriverWait wait = new WebDriverWait(driver, 10);
    wait.until(ExpectedConditions.visibilityOf(welcomeHeader));
    switchToNativeContext(); // write yourself :-)
}
2 Likes

@Aleksei great thx for the help