Best io.appium code snippet using io.appium.java_client.remote.SupportsContextSwitching.getContext
GenericWebDriverManagerTests.java
Source:GenericWebDriverManagerTests.java  
...71    private void mockMobileDriverContext(SupportsContextSwitching contextSwitchingDriver,72            Set<String> returnContextHandles)73    {74        when(webDriverProvider.getUnwrapped(SupportsContextSwitching.class)).thenReturn(contextSwitchingDriver);75        when(contextSwitchingDriver.getContext()).thenReturn(WEBVIEW_CONTEXT);76        when(contextSwitchingDriver.getContextHandles()).thenReturn(returnContextHandles);77    }78    private GenericWebDriverManager spyIsMobile(boolean returnValue)79    {80        var spy = Mockito.spy(driverManager);81        doReturn(returnValue).when(spy).isMobile();82        return spy;83    }84    @Test85    void testPerformActionInNativeContextNotMobile()86    {87        var webDriverConfigured = mock(WebDriver.class);88        when(webDriverProvider.get()).thenReturn(webDriverConfigured);89        GenericWebDriverManager spy = spyIsMobile(false);90        spy.performActionInNativeContext(webDriver -> assertEquals(webDriverConfigured, webDriver));91        verifyNoInteractions(webDriverConfigured);92    }93    @Test94    void testPerformActionInNativeContext()95    {96        var contextSwitchingDriver = mock(SupportsContextSwitching.class,97                withSettings().extraInterfaces(HasCapabilities.class));98        Set<String> contexts = new HashSet<>();99        contexts.add(WEBVIEW_CONTEXT);100        contexts.add(NATIVE_APP_CONTEXT);101        mockMobileDriverContext(contextSwitchingDriver, contexts);102        var spy = spyIsMobile(true);103        spy.performActionInNativeContext(webDriver -> assertEquals(contextSwitchingDriver, webDriver));104        verify(contextSwitchingDriver).context(NATIVE_APP_CONTEXT);105        verify(contextSwitchingDriver).context(WEBVIEW_CONTEXT);106    }107    @Test108    void testPerformActionInNativeContextException()109    {110        var contextSwitchingDriver = mock(SupportsContextSwitching.class,111                withSettings().extraInterfaces(HasCapabilities.class));112        mockMobileDriverContext(contextSwitchingDriver, new HashSet<>());113        var spy = spyIsMobile(true);114        var exception = assertThrows(IllegalStateException.class,115                () -> spy.performActionInNativeContext(webDriver -> assertEquals(contextSwitchingDriver, webDriver)));116        assertEquals("MobileDriver doesn't have context: " + NATIVE_APP_CONTEXT, exception.getMessage());117    }118    @Test119    void testPerformActionInNativeContextSwitchNotNeeded()120    {121        var contextSwitchingDriver = mock(SupportsContextSwitching.class);122        when(webDriverProvider.getUnwrapped(SupportsContextSwitching.class)).thenReturn(contextSwitchingDriver);123        when(contextSwitchingDriver.getContext()).thenReturn(NATIVE_APP_CONTEXT);124        var spy = spyIsMobile(true);125        spy.performActionInNativeContext(webDriver -> assertEquals(contextSwitchingDriver, webDriver));126        verify(contextSwitchingDriver, never()).context(NATIVE_APP_CONTEXT);127        verify(contextSwitchingDriver, never()).getContextHandles();128    }129    static Stream<Arguments> mobileArguments()130    {131        // CHECKSTYLE:OFF132        return Stream.of(133            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isMobile, MobilePlatform.IOS, true),134            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isMobile, MobilePlatform.ANDROID, true),135            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isMobile, MobilePlatform.WINDOWS, false),136            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isMobile, Platform.IOS, true),137            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isMobile, Platform.ANDROID, true),138            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isMobile, Platform.WINDOWS, false),139            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOS, MobilePlatform.IOS, true),140            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOS, MobilePlatform.ANDROID, false),141            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOS, Platform.IOS, true),142            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOS, Platform.ANDROID, false),143            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isAndroid, MobilePlatform.IOS, false),144            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isAndroid, MobilePlatform.ANDROID, true),145            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isAndroid, Platform.IOS, false),146            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isAndroid, Platform.ANDROID, true),147            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isTvOS, MobilePlatform.TVOS, true),148            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isTvOS, MobilePlatform.IOS, false),149            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isTvOS, Platform.IOS, false),150            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOS, null, false)151        );152        // CHECKSTYLE:ON153    }154    @ParameterizedTest155    @MethodSource("mobileArguments")156    void testIsPlatform(Predicate<GenericWebDriverManager> test, Object platform, boolean expected)157    {158        mockWebDriver(platform);159        assertEquals(expected, test.test(driverManager));160    }161    static Stream<Arguments> mobileNativeArguments()162    {163        // CHECKSTYLE:OFF164        return Stream.of(165                arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isAndroidNativeApp, MobilePlatform.ANDROID, true),166                arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isAndroidNativeApp, MobilePlatform.IOS, false),167                arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOSNativeApp, MobilePlatform.IOS, true),168                arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOSNativeApp, "ios", true),169                arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOSNativeApp, MobilePlatform.ANDROID, false)170        );171        // CHECKSTYLE:ON172    }173    @ParameterizedTest174    @MethodSource("mobileNativeArguments")175    void testIsMobileNativeApp(Predicate<GenericWebDriverManager> test, Object platform, boolean expected)176    {177        driverManager.setMobileApp(true);178        mockWebDriver(platform);179        assertEquals(expected, test.test(driverManager));180    }181    static Stream<Arguments> notMobileNativeArguments()182    {183        return Stream.of(184                arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isAndroidNativeApp),185                arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOSNativeApp)186        );187    }188    @ParameterizedTest189    @MethodSource("notMobileNativeArguments")190    void testIsNotMobileNativeApp(Predicate<GenericWebDriverManager> test)191    {192        driverManager.setMobileApp(false);193        assertFalse(test.test(driverManager));194    }195    @Test196    void testGetSize()197    {198        WebDriver webDriver = mockWebDriver(Platform.WINDOWS);199        var screenSize = mock(Dimension.class);200        mockSizeRetrieval(webDriver, screenSize);201        assertEquals(screenSize, driverManager.getSize());202    }203    @Test204    void shouldGetScreenSizeForMobileApp()205    {206        var dimension = new Dimension(375, 667);207        var iOSDriver = mock(IOSDriver.class);208        lenient().when(webDriverProvider.getUnwrapped(SupportsContextSwitching.class)).thenReturn(iOSDriver);209        when(iOSDriver.getContext()).thenReturn(NATIVE_APP_CONTEXT);210        mockWebDriver(MobilePlatform.IOS);211        mockSizeRetrieval(iOSDriver, dimension);212        assertEquals(dimension, driverManager.getSize());213        verify(webDriverManagerContext).putParameter(WebDriverManagerParameter.SCREEN_SIZE, dimension);214    }215    private void mockSizeRetrieval(WebDriver webDriver, Dimension screenSize)216    {217        var options = mock(Options.class);218        when(webDriver.manage()).thenReturn(options);219        var window = mock(Window.class);220        when(options.window()).thenReturn(window);221        when(window.getSize()).thenReturn(screenSize);222    }223    @Test...GenericWebDriverManager.java
Source:GenericWebDriverManager.java  
...70    {71        if (isMobile())72        {73            SupportsContextSwitching contextSwitchingDriver = getUnwrappedDriver(SupportsContextSwitching.class);74            String originalContext = contextSwitchingDriver.getContext();75            if (!NATIVE_APP_CONTEXT.equals(originalContext))76            {77                switchToContext(contextSwitchingDriver, NATIVE_APP_CONTEXT);78                try79                {80                    return function.apply(contextSwitchingDriver);81                }82                finally83                {84                    switchToContext(contextSwitchingDriver, originalContext);85                }86            }87            return function.apply(contextSwitchingDriver);88        }89        return function.apply(webDriverProvider.get());90    }91    private void switchToContext(ContextAware contextAwareDriver, String contextName)92    {93        if (contextAwareDriver.getContextHandles().contains(contextName))94        {95            contextAwareDriver.context(contextName);96        }97        else98        {99            throw new IllegalStateException("MobileDriver doesn't have context: " + contextName);100        }101    }102    @Override103    public boolean isMobile()104    {105        Capabilities capabilities = getCapabilities();106        return isIOS(capabilities) || isAndroid(capabilities);107    }...SupportsContextSwitching.java
Source:SupportsContextSwitching.java  
...47     * Get the names of available contexts.48     *49     * @return List list of context names.50     */51    default Set<String> getContextHandles() {52        Response response = execute(DriverCommand.GET_CONTEXT_HANDLES, ImmutableMap.of());53        Object value = response.getValue();54        try {55            //noinspection unchecked56            List<String> returnedValues = (List<String>) value;57            return new LinkedHashSet<>(returnedValues);58        } catch (ClassCastException ex) {59            throw new WebDriverException(60                    "Returned value cannot be converted to List<String>: " + value, ex);61        }62    }63    /**64     * Get the name of the current context.65     *66     * @return Context name or null if it cannot be determined.67     */68    @Nullable69    default String getContext() {70        String contextName =71                String.valueOf(execute(DriverCommand.GET_CURRENT_CONTEXT_HANDLE).getValue());72        return "null".equalsIgnoreCase(contextName) ? null : contextName;73    }74}...getContext
Using AI Code Generation
1package appium;2import java.net.MalformedURLException;3import java.net.URL;4import java.util.Set;5import org.openqa.selenium.By;6import org.openqa.selenium.remote.DesiredCapabilities;7import io.appium.java_client.android.AndroidDriver;8import io.appium.java_client.android.AndroidElement;9import io.appium.java_client.remote.MobileCapabilityType;10public class contextswitching {11	public static void main(String[] args) throws MalformedURLException {12		DesiredCapabilities cap = new DesiredCapabilities();13		cap.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Device");14		cap.setCapability("appPackage", "com.androidsample.generalstore");15		cap.setCapability("appActivity", ".SplashActivity");getContext
Using AI Code Generation
1SupportsContextSwitching contextSwitching = (SupportsContextSwitching) driver;2String context = contextSwitching.getContext();3System.out.println("Current context is: " + context);4SupportsContextSwitching contextSwitching = (SupportsContextSwitching) driver;5Set<String> contexts = contextSwitching.getContextHandles();6System.out.println("Available contexts are: " + contexts);7SupportsContextSwitching contextSwitching = (SupportsContextSwitching) driver;8contextSwitching.switchTo().context("NATIVE_APP");9driver.context('WEBVIEW_1')10driver.switch_to.context('WEBVIEW_1')11driver.context('WEBVIEW_1')12driver.switchTo().context('WEBVIEW_1')13driver.context('WEBVIEW_1')14driver.switch_to.context('WEBVIEW_1')15driver.context('WEBVIEW_1')16driver.switchTo().context('WEBVIEW_1')17$driver->context('WEBVIEW_1');18$driver->contexts();getContext
Using AI Code Generation
1driver.context("NATIVE_APP");2driver.context("WEBVIEW_1");3driver.context("WEBVIEW_2");4driver.context("NATIVE_APP")5driver.context("WEBVIEW_1")6driver.context("WEBVIEW_2")7driver.context("NATIVE_APP")8driver.context("WEBVIEW_1")9driver.context("WEBVIEW_2")10driver.context("NATIVE_APP")11driver.context("WEBVIEW_1")12driver.context("WEBVIEW_2")13$driver->context("NATIVE_APP");14$driver->context("WEBVIEW_1");15$driver->context("WEBVIEW_2");16driver.context("NATIVE_APP")17driver.context("WEBVIEW_1")18driver.context("WEBVIEW_2")19driver.context("NATIVE_APP");20driver.context("WEBVIEW_1");21driver.context("WEBVIEW_2");22driver.context("NATIVE_APP");23driver.context("WEBVIEW_1");24driver.context("WEBVIEW_2");25driver.context("NATIVE_APP")26driver.context("WEBVIEW_1")27driver.context("WEBVIEW_2")28driver.context("NATIVE_APP")29driver.context("WEBVIEW_1")30driver.context("WEBVIEW_2")31driver.context("NATIVE_APP")32driver.context("WEBVIEW_1")33driver.context("WEBVIEW_2")34driver.context("NATIVE_APP")35driver.context("WEBgetContext
Using AI Code Generation
1import io.appium.java_client.AppiumDriver;2import io.appium.java_client.android.AndroidDriver;3import io.appium.java_client.remote.MobileCapabilityType;4import io.appium.java_client.remote.MobilePlatform;5import org.openqa.selenium.remote.DesiredCapabilities;6import java.net.URL;7import java.net.MalformedURLException;8import java.util.concurrent.TimeUnit;9import io.appium.java_client.remote.SupportsContextSwitching;10import org.openqa.selenium.WebElement;11import org.openqa.selenium.By;12public class Appium {13    public static void main(String[] args) {14        DesiredCapabilities capabilities = new DesiredCapabilities();15        capabilities.setCapability("deviceName", "Android Emulator");16        capabilities.setCapability(CapabilityType.BROWSER_NAME, "Android");17        capabilities.setCapability(CapabilityType.VERSION, "4.4.2");18        capabilities.setCapability("platformName", "Android");19        capabilities.setCapability("appPackage", "com.android.calculator2");20        capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");getContext
Using AI Code Generation
1public class AppiumJavaClient {2    public static void main(String[] args) throws MalformedURLException {3        DesiredCapabilities caps = new DesiredCapabilities();4        caps.setCapability("platformName", "Android");5        caps.setCapability("deviceName", "emulator-5554");6        caps.setCapability("appPackage", "com.androidsample.generalstore");7        caps.setCapability("appActivity", ".SplashActivity");8        caps.setCapability("noReset", "true");9        caps.setCapability("automationName", "uiautomator2");10        caps.setCapability("chromedriverExecutable", "C:\\Users\\Selenium\\Downloads\\chromedriver_win32\\chromedriver.exe");Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
