diff --git a/README.md b/README.md index 71a2816..98ac1b8 100644 --- a/README.md +++ b/README.md @@ -249,6 +249,14 @@ public class Test { } ``` +## Changing application context +In certain scenarios, applications may switch contexts, which can be necessary for automation purposes. +Utilize the following function to switch the application context: + +```java +switchApplicationContext(""); // Pass the application context to switch to +``` + ## Elements Same element can be defined for all the platforms, i.e. same element definition diff --git a/src/main/java/testUI/TestUIDriver.java b/src/main/java/testUI/TestUIDriver.java index c7834f3..0704ba1 100644 --- a/src/main/java/testUI/TestUIDriver.java +++ b/src/main/java/testUI/TestUIDriver.java @@ -12,12 +12,10 @@ import testUI.elements.TestUI; import testUI.elements.UIElement; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import static testUI.UIUtils.*; +import static testUI.Utils.Logger.putLogInfo; public class TestUIDriver { private static ThreadLocal> driver = new ThreadLocal<>(); @@ -225,4 +223,43 @@ public static DesiredCapabilities getDesiredCapabilities() { public static UIElement getTestUIDriver() { return TestUI.E(""); } + + public static void switchApplicationContext(String context) { + AppiumDriver driver = getDriver(); + + if (driver instanceof AndroidDriver) { + AndroidDriver androidDriver = (AndroidDriver) driver; + Set contextNames = androidDriver.getContextHandles(); + + boolean contextFound = false; + for (String contextName : contextNames) { + if (contextName.contains(context)) { + androidDriver.context(contextName); + putLogInfo("Switched to context: " + contextName); + contextFound = true; + break; + } + } + if (!contextFound) { + putLogInfo("Provided context is not available"); + } + } else if (driver instanceof IOSDriver) { + IOSDriver iosDriver = (IOSDriver) driver; + Set contextNames = iosDriver.getContextHandles(); + boolean contextFound = false; + for (String contextName : contextNames) { + if (contextName.contains(context)) { + iosDriver.context(contextName); + putLogInfo("Switched to context: " + contextName); + contextFound = true; + break; + } + } + if (!contextFound) { + putLogInfo("Provided context is not available"); + } + } else { + putLogInfo("Unsupported driver type."); + } + } }